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

Problems with creating text files with ofstream in C++

本文关键字:文本 文件 问题 创建 ofstream c++      更新时间:2023-10-16

我正在遵循一本c++教科书,目前在处理ofstreamifstream的部分。我在同一个项目的main()函数中键入了几个例子(CodeBlocks 13.12)。

问题是开头的一些代码工作得很好,而其余的代码则不行。我试着在下面的代码后面解释它:

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"没有被创建。

谁能给我解释一下为什么部分代码不能工作?以及如何纠正它,或者为了将来的参考需要注意什么?

In

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

你退出(return 0)时,测试"MyFile.dat"的成功打开。

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);