C++如何在不使用winapi的情况下将文件从一个磁盘移动并复制到不同的磁盘
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
之类的东西之外,我不相信还有其他标准的、可移植的方法可以删除文件。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 如何从整个磁盘中排除要装载的一个文件
- 如何使用PHP将上传到本地主机的一个html文件重定向到磁盘上的另一个html文档
- 从RAM向磁盘写入一个大文件
- 执行一个新的完全独立的进程,该进程封装在一个可执行文件中,而不需要为独立进程将文件写入磁盘
- 以RAW形式恢复磁盘内容并转储为一个大二进制文件的应用程序
- WriteFile函数如何与磁盘上的另一个数据交互
- C++如何在不使用winapi的情况下将文件从一个磁盘移动并复制到不同的磁盘
- 如果一个程序的主要功能是从磁盘中读取数据,那么让它多线程是不是一个好主意?
- 如何将一个大的二进制文件写入磁盘
- 在磁盘上的JSON文件中追加一个JSON数组,每秒使用c++
- 有可能用C或c++实现一个小的磁盘操作系统吗?
- 如何在Matlab中训练一个模型,将其保存到磁盘,并在c++中加载程序
- 获取一个FILE *句柄而不实际在磁盘上创建一个文件