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

时间:2014-07-30 16:37:01

标签: c++ file-io fstream ifstream ofstream

我正在关注C ++教科书,目前正在处理 ofstream ifstream 的部分。我在项目的相同 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”

有人可以解释我为什么部分代码不起作用?以及如何纠正它,或者需要关注哪些以供将来参考?

1 个答案:

答案 0 :(得分:4)

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