C++如何在不使用winapi的情况下将文件从一个磁盘移动并复制到不同的磁盘

C++ how to move files and copy them from one disk to different without the usage of winapi?

本文关键字:磁盘 一个 移动 复制 文件 winapi C++ 情况下      更新时间:2023-10-16

它必须是纯的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之类的东西之外,我不相信还有其他标准的、可移植的方法可以删除文件。