我正在学习 C++ 教科书,目前在处理 ofstream 和 ifstream 的部分。我在一个项目 (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/