C++如何在不使用 winapi 的情况下移动文件并将其从一个磁盘复制到另一个磁盘?
它必须是纯c++,我知道system("copy c:\\test.txt d:\\test.txt"
);但我认为这是系统函数,而不是c++解决方案,否则我会出错吗?
It must be pure c++, I know about system("copy c:\\test.txt d:\\test.txt"
); but I think it's the system function, not c++ solution, or I can mistakes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
std::fstream
怎么样?打开一个用于读取,另一个用于写入,并使用std::copy
让标准库处理复制。像这样的事情:
How about
std::fstream
? Open one for reading and another for writing, and usestd::copy
to let the standard library handle the copying.Something like this:
尝试使用 boost 中的
copy_file
。如果有错误,它会抛出异常。有关更多文档,请参阅此页面:http: //www.boost.org/doc/libs/1_48_0/libs/filesystem/v3/doc/reference.html#copy_file
Try using
copy_file
from boost.It will throw an exception if there is an error. See this page for more documentation: http://www.boost.org/doc/libs/1_48_0/libs/filesystem/v3/doc/reference.html#copy_file
我喜欢使用标准 STL 运算符的简单流方法:
这里的想法是有一个
operator<< (streambuf*)
用于std::ofstream
,因此您只需将与输入流关联的streambuf
传递给它即可。为了完整起见,您可以执行如下操作:
如果目标尚不存在,则只会复制文件。只是对完整性进行额外检查:)
关于移动文件,在“标准”C++中,我可能会复制该文件(如上所述),然后删除它,执行以下操作:
除了使用诸如
boost
我不相信还有另一种标准的、可移植的方法来删除文件。I like the simple streaming approach, using standard STL operators:
The idea here is that there is an
operator<< (streambuf*)
forstd::ofstream
, so you simply pass it thestreambuf
associated with your input stream.For completeness, you could do something like the following:
This would only copy the file if the destination didn't already exist. Just an extra check for sanity :)
Regarding moving a file, in "standard" C++ I would probably copy the file (as above), and then delete it, doing something like:
Aside from using something like
boost
I'm not convinced there's another standard, portable way to delete a file.