【发布时间】:2014-07-30 16:37:00
【问题描述】:
我正在关注一本 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" 不会被创建。
谁能解释一下为什么部分代码不起作用?以及如何纠正它,或者要注意什么以备将来参考?
【问题讨论】:
-
您似乎已将代码设计为提前退出,因为它找到了现有文件。
-
@RetiredNinja - 你能指出发生这种情况的实例吗?我从教科书中复制了代码,并没有提到任何退出。
标签: c++ file-io fstream ifstream ofstream