如何在 c/c++ 中将文件从一个目录复制到另一个目录
我正在寻找一个关于如何在 C 中将文件从一个目录复制到另一个目录的简单示例。该程序应该只使用 C 原生的跨平台函数。
I am looking for a simple example on how to copy a file from one directory to another in C. The program should only use cross platform functions that are native to C.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这是一个简单的未经测试的 C 程序,可以满足您的需要:
Here is a simple untested C program that does what you need:
我相信你能做到!
I'm sure you can do it!
使用 dirent.h 在 C++ 中复制文件的正确方法如下。请注意,dirent.h 是 Linux 的一部分,但不包含在 Windows 中。对于 Windows,请查看此处。
对于 Windows Visual C++:
对于 Linux Eclipse C++:
Visual Studio C++ dll:
对于 dll,您可以按如下方式调用它:
VB.Net:Visual
C#:
The correct way to copy files in C++ using dirent.h is below. Note that dirent.h is part of Linux but not included in Windows. For Windows look here.
For Windows Visual C++:
For Linux Eclipse C++:
Visual Studio C++ dll:
For the dll, you call call it as following:
VB.Net:
Visual C#:
@Mu Qiao 提到了
boost::filesystem
。具体来说,您需要查找copy_file
的示例,尽管您也可以复制目录。如果您对异步 I/O 感兴趣,我的印象是
boost::asio
有有趣的实现,利用平台功能让您在等待磁盘时使用 CPU,就像网络一样:如何执行交叉-平台异步文件C++ 中的 I/O
(注意:最近我经常想到 asio 库,但我总是必须提供免责声明,即我没有在项目中使用过它,并且有点不知道它的局限性是什么。所以请对我提到的持保留态度。)
还有其他跨平台库提供这种功能,如果您愿意购买的话,总是可以的。品味和需求的问题。我自己喜欢 Qt 有很多原因,而且它确实提供了
QFile::copy
方法:http://doc.qt.nokia.com/latest/qfile.html#copy
@Mu Qiao mentioned
boost::filesystem
. Specifically you'd want to look for examples ofcopy_file
, though you can copy directories too.If you're interested in getting fancy with asynchronous I/O, my impression is that
boost::asio
has interesting implementations that take advantage of platform abilities to let you use the CPU while waiting for the disk, just as it does for the network:How to perform Cross-Platform Asynchronous File I/O in C++
(Note: Lately the asio library has been coming to mind lately a lot, but I always have to offer the disclaimer that I haven't used it in a project and kind of have no idea what its limitations are. So take my mention of it with a grain of salt.)
There are other cross-platform libraries offering this kind of functionality, if you're willing to do the buy-in, always a matter of taste and needs. I myself like Qt for a lot of reasons, and it does happen to offer a
QFile::copy
method:http://doc.qt.nokia.com/latest/qfile.html#copy
另一种选择是这样的:
...
Another alternative is something like this:
...
我对 @te7 答案做了一些更改,仅将一个文件从 MAC 上的一个文件夹复制到另一个文件夹。我尝试修改他的代码以仅复制一个文件,但它部分地将文件写入目标。所以我使用不同的代码来读取/写入文件
I made some changes to @te7 answer to copy just one file from one folder to another on MAC. I tried to modify his code to just copy one file but it was partially writing file to destination. So I use different code for file read/write