Uko
Uko

Reputation: 13396

Copy directory recursively in pure C on Linux/UNIX

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

Answers (3)

Ashu Pachauri
Ashu Pachauri

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

Fred Foo
Fred Foo

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

Niklas B.
Niklas B.

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:

  • Open source file
  • Open target file
  • In a loop, fread a block of constant size from the source, then fwrite it to the target. Stop if the source file contains no more data

Hope this helps :)

Upvotes: 2

Related Questions