gpt4 book ai didi

c++ - C++ 将一个文件的内容复制到另一个文件

转载 作者:可可西里 更新时间:2023-11-01 14:46:42 25 4
gpt4 key购买 nike

我正在使用以下程序尝试将文件 src 的内容复制到 C++ 中的另一个文件 dest。简化代码如下:

#include <fstream>
using namespace std;
int main()
{
fstream src("c:\\tplat\test\\secClassMf19.txt", fstream::binary);
ofstream dest("c:\\tplat\\test\\mf19b.txt", fstream::trunc|fstream::binary);
dest << src.rdbuf();
return 0;
}

当我在 Windows 中使用 CODEBLOCKS ide 和 GCC 编译器构建并执行程序时,创建了一个名为“....mf19.txt”的新文件,但没有数据被复制到其中,文件大小 = 0kb。我确定“...secClassMf19.txt”中有一些数据。

我在windows Visual C++ 2008中编译同样的程序时遇到了同样的问题。

任何人都可以帮助解释为什么我会遇到这种意外行为,更重要的是,如何解决这个问题?

最佳答案

在使用这些流之前,您需要检查打开文件是否真正成功。此外,检查之后是否一切正常也没有坏处。将您的代码更改为此并报告:

int main()
{
std::fstream src("c:\\tplat\test\\secClassMf19.txt", std::ios::binary);
if(!src.good())
{
std::cerr << "error opening input file\n";
std::exit(1);
}
std::ofstream dest("c:\\tplat\\test\\mf19b.txt", std::ios::trunc|std::ios::binary);
if(!dest.good())
{
std::cerr << "error opening output file\n";
std::exit(2);
}
dest << src.rdbuf();
if(!src.eof())
std::cerr << "reading from file failed\n";
if(!dst.good())
std::cerr << "writing to file failed\n";
return 0;
}

我打赌您会报告前两个检查中的一个成功。

如果打开输入文件失败,请尝试使用 std::ios::in|std::ios::binary 而不是仅使用 std::ios::binary< 打开它

关于c++ - C++ 将一个文件的内容复制到另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3820483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com