c++ - 在 C++ 中使用 ofstream 创建文本文件的问题

标签 c++ file-io fstream ifstream ofstream

我正在学习 C++ 教科书,目前在处理 ofstreamifstream 的部分。我在一个项目 (CodeBlocks 13.12) 的相同 main() 函数中键入了几个示例。

问题是开头的一些代码可以正常工作,而其余部分则不能。我试着在下面解释它,在代码之后。:

ofstream outfile("MyFile.dat");  

if (!outfile) 
{
cout << "Couldn’t open the file!" << endl;
}

outfile << "Hi" << endl;
outfile.close();

ofstream outfile2("MyFile.dat", ios_base::app); 
outfile2 << "Hi again" << endl; 
outfile2.close();


ifstream infile("MyFile.dat");
if (infile.fail())
{
cout << "Couldn't open the file!" << endl;
return 0;
}
infile.close();
ofstream outfile3("MyFile.dat", ios_base::app);
outfile3 << "Hey" << endl;
outfile3.close();


string word;
ifstream infile2("MyFile.dat");
infile2 >> word; 
cout << word << endl; // "Hi" gets printed, I suppose it only prints 1st line ?
infile2.close();


ifstream infile3("MyFile.dat");
if (!infile3.fail())
{
cout << endl << "The file already exists!" << endl;
return 0;
}
infile3.close();
ofstream outfile4("MyFile.dat");
outfile4 << "Hi Foo" << endl; 
outfile4.close();
// this piece of code erases everything in MyFile.dat - why ?


ofstream outfile5("outfile5.txt");
outfile5 << "Lookit me! I’m in a file!" << endl;
int x = 200;
outfile5 << x << endl;
outfile5.close();

当代码执行时,唯一创建的文件是MyFile.dat,其内容是

Hi
Hi again
Hey

“Hi Foo”未写入文件,“outfile5.txt”未创建。

有人可以向我解释为什么部分代码不起作用吗?以及如何更正它,或者需要注意什么以供将来引用?

最佳答案

ifstream infile3("MyFile.dat");
if (!infile3.fail())
{
    cout << endl << "The file already exists!" << endl;
    return 0;
}

每当测试成功打开"MyFile.dat" 时退出(返回 0)。

ofstream outfile4("MyFile.dat");
outfile4 << "Hi Foo" << endl; 
outfile4.close();
// this piece of code erases everything in MyFile.dat - why ?

“MyFile.dat”的内容正在被删除,因为默认情况下您打开流进行重写,而不是追加。如果要追加,请使用

outfile.open("MyFile.txt", std::ios_base::app);

关于c++ - 在 C++ 中使用 ofstream 创建文本文件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25042271/

相关文章:

c++ - 使用Doxygen制作Visual Studio和Emacs的文档

c++ - 从多个 C/C++ 线程调用 Haskell

file-io - 在 Clojure 中拖尾文件?

java - 如何在 src/main/resources 中创建文件

c++ - 为什么这个数据流在第 26 个字节结束?

c++ - 如何在 ListView 中显示每个项目的所有 QComboBoxes?

c++ - 从函数返回一个带有值模板参数的类模板

python - 创建文件,但如果名称存在则添加编号

c++ - 如何使用 C++ 将文本文件的不同部分上传到不同的数组