如何在不使用WinAPI的情况下移动和复制C++文件到不同磁盘?

4

必须是纯c++,我知道有 "copy c:\\test.txt d:\\test.txt" 这样的 system 函数;但是我认为那是系统函数,并不是c++解决方案。或者我错了吗?

3个回答

3

那么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));
}

无法编译,因为istream_iterator和ostream_iterator是类模板,需要模板参数列表。 - palota

3

2
我喜欢简单的流处理方式,使用标准的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这样的东西,我不确定是否有另一种标准、可移植的方法来删除文件。


它能处理任何文件还是只有txt格式的文件?如果我需要将例如C:\song.mp3移动到D:\song.mp3,它能正常工作吗? - Marius
它应该适用于任何文件类型。以防万一,我将更改示例以二进制方式读取文件。 - icabod

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接