std::ofstream 附加文件

Rol*_*and 3 c++ fstream

所以我想在文件中输入一些东西,但它似乎不起作用。我的代码是这样的:

  ofstream f("reservedTables.DAT");  
  cin >> table;
  f.open("reservedTables.DAT", ios::out | ios::app);
  f << table;
  f.close();
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我写了变量的数字table,但它没有出现在我放入的文件中

use*_*301 5

快速浏览:

ofstream f("reservedTables.DAT");  
Run Code Online (Sandbox Code Playgroud)

分配流并打开文件。

cin >> table;
Run Code Online (Sandbox Code Playgroud)

读取用户的输入。

f.open("reservedTables.DAT", ios::out | ios::app);
Run Code Online (Sandbox Code Playgroud)

尝试重新打开文件。将失败。

f << table;
Run Code Online (Sandbox Code Playgroud)

打开失败后,流处于失败状态,无法写入。

f.close();
Run Code Online (Sandbox Code Playgroud)

关闭文件。

解决方案

仅打开文件一次并检查是否有错误。

ofstream f("reservedTables.DAT", ios::app); // no need for ios::out. 
                                            // Implied by o in ofstream  
cin >> table;
if (f.is_open()) // make sure file opened before writing
{
    if (!f << table) // make sure file wrote
    {
        std::cerr << "Oh snap. Failed write".
    }
    f.close(); // may not be needed. f will automatically close when it 
               // goes out of scope
}
else
{
    std::cerr << "Oh snap. Failed open".
}
Run Code Online (Sandbox Code Playgroud)