Copy directory recursively in pure C on Linux/UNIX

穿精又带淫゛_ 提交于 2019-12-08 02:56:27

问题


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


回答1:


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 :)




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/9192295/copy-directory-recursively-in-pure-c-on-linux-unix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!