【问题标题】:Problems with creating text files with ofstream in C++在 C++ 中使用 ofstream 创建文本文件的问题
【发布时间】:2014-07-30 16:37:00
【问题描述】:

我正在关注一本 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" 不会被创建。

谁能解释一下为什么部分代码不起作用?以及如何纠正它,或者要注意什么以备将来参考?

【问题讨论】:

  • 您似乎已将代码设计为提前退出,因为它找到了现有文件。
  • @RetiredNinja - 你能指出发生这种情况的实例吗?我从教科书中复制了代码,并没有提到任何退出。

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


【解决方案1】:

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

每当测试"MyFile.dat" 的成功打开时,您都会退出 (return 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);

【讨论】:

  • 感谢您的回答,这解决了主要问题。但是,如果我没有要求太多,您能否看一下以注释结尾的代码部分:“// 这段代码会擦除 MyFile.dat 中的所有内容 - 为什么?” ,并尝试扩展您的答案并对此进行解释?谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多