Advertisement

Copying files with function calls

Started by September 11, 2006 07:11 AM
1 comment, last by let_bound 18 years, 2 months ago
I'm working on an individual project for uni (an actual subject where all you do is complete a project of sorts), and at one point, I need to copy a binary file from one directory to another, and I would prefer to be able to do it without using 'system', and also without simply opening a file pointer and just copying byte by byte. I haven't been able to find out anything about it after a little bit of googling. Does anyone have any ideas? I know that you can open a stream to a directory through a DIR*, but I haven't been able to find any information on those apart from the fact that they exist. I was previously able to use the 'scandir' function to read the names of the different files from a directory, but that doesn't help me in copying a file. Oh, and just in case you were wondering, the project has to do with feature recognition and image processing, so if you give me an answer, you're not helping me "cheat." [smile]
[size="2"][size=2]Mort, Duke of Sto Helit: NON TIMETIS MESSOR -- Don't Fear The Reaper
If you just want to rename the file within a single filesystem, try rename(2). You cannot rename across filesystems, since all you're doing is associating a different label wit hthe file's inode.

If you want to copy a file or move it across filesystems, your choices are (1) launch an external command using system(3), (2) avoind using the shell by going the fork(2)/exec(2) route and executing /usr/bin/cp directly yourself, or (3) opening the file and copying byte for byte. It's 3 lines of C++ code using the standard library.

There's no alternative to copying a file other than copying the file.

Stephen M. Webb
Professional Free Software Developer

Advertisement
It depends what you need the file for. You could use link(2) to create a new (hard) link to the i-node, and then unlink(2) the original file. That should be much faster than copying the file around, but it will only work if the source and destination are on the same filesystem.

You could also use symlink(2), but then you can't delete the original file, otherwise you'll have a broken link.

Keep in mind that the new "file" will reference the same i-node as the original file. Modifying either the original or the new file will also modify the other one.

Hope this helps.

EDIT: added the last paragraph.


[Edited by - let_bound on September 11, 2006 11:46:01 AM]

This topic is closed to new replies.

Advertisement