Reputation: 13396
Can someone guide me on a possible solution? I don't want to use /bin/cp
or any other foreign apps. I want my program to be independent. Also I know that every system is quite specific, so I'm interested in UNIX/Linux compatibility.
How can I solve it? Just going down the source directory and creating a new directories in the target one and copying files in them, or there is a better solution?
BTW my goal is: copy all first level subdirs recursively into target dir if they are not present there
Upvotes: 2
Views: 9352
Reputation: 1403
If you want to use only C, you could use dirent.h. Using this, you can recursively follow the directory structure. Then you could open the files in the binary mode, and write them to the desired location via write stream.
Upvotes: 0
Reputation: 363818
Use the POSIX nftw(3)
function to walk the tree you want to copy. You supply this function with a callback function that gets called on the path of each file/directory. Define a callback that copies the file/dir it gets called on into the destination tree. The fourth callback argument of type struct FTW *
can be used to compute the relative path.
Upvotes: 1
Reputation: 95358
You really need some kind of recursive descent into the directory tree. Doing this, you can actually make this very portable (using opendir
/readdir
on Linux and FindFirstFile
/FindNextFile
on Windows). The problem that remains is the actual copying. You can use the C standard library for that with the following algorithm:
fread
a block of constant size from the source, then fwrite
it to the target. Stop if the source file contains no more dataHope this helps :)
Upvotes: 2