[英]How to copy multiple files from server to local hard disk in one http request using C++?
[英]C++ how to move files and copy them from one disk to different without the usage of winapi?
它必须是纯c ++ ,我知道系统( "copy c:\\\\test.txt d:\\\\test.txt"
); 但我认为这是系统功能,而不是c ++解决方案,或者我可以犯错误?
std::fstream
怎么样? 打开一个用于读取,另一个用于写入,并使用std::copy
让标准库处理复制。
像这样的东西:
void copy_file(const std::string &from, const std::string &to)
{
std::ifstream is(from, ios::in | ios::binary);
std::ofstream os(to, ios::out | ios::binary);
std::copy(std::istream_iterator<char>(is), std::istream_iterator<char>(),
std::ostream_iterator<char>(os));
}
尝试使用boost中的 copy_file
。
#include <boost/filesystem.hpp>
boost::filesystem::copy_file("c:\\test.txt","d:\\test.txt");
如果出现错误,它将抛出异常。 有关更多文档,请参阅此页面: http : //www.boost.org/doc/libs/1_48_0/libs/filesystem/v3/doc/reference.html#copy_file
我喜欢使用标准STL运算符的简单流式处理方法:
std::ifstream ifs("somefile", std::ios::in | std::ios::binary);
std::ofstream ofs("newfile", std::ios::out | std::ios::binary);
ofs << ifs.rdbuf();
这里的想法是std::ofstream
有一个operator<< (streambuf*)
,所以你只需要传递与你的输入流相关的streambuf
。
为了完整起见,您可以执行以下操作:
bool exists(const std::string& s) {
std::ifstream istr(s, std::ios::in | std::ios::binary);
return istr.is_open();
}
void copyfile(const std::string& from, const std::string& to) {
if (!exists(to)) {
std::ifstream ifs(from, std::ios::in | std::ios::binary);
std::ofstream ofs(to, std::ios::out | std::ios::binary);
ofs << ifs.rdbuf();
}
}
如果目标尚不存在,这只会复制文件。 只是额外检查理智:)
关于移动文件,在“标准”C ++中,我可能会复制文件(如上所述),然后将其删除,执行以下操作:
if (0 != remove(from.c_str())) {
// remove failed
}
除了使用像boost
这样的东西之外我还不相信还有另一种标准的,可移植的删除文件的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.