我正在使用以下程序尝试将文件 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
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)