Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::ofstream appending files

Tags:

c++

fstream

So I want to input something in a file but it doesn't seem to work. My code is this:

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

What am I doing wrong? I write the number for the variable table but it doesn't appear in the file that I put it in

like image 685
Roland Avatar asked Apr 13 '26 13:04

Roland


1 Answers

Quick walk through:

ofstream f("reservedTables.DAT");  

Allocates stream and opens the file.

cin >> table;

Reads in input from user.

f.open("reservedTables.DAT", ios::out | ios::app);

Attempts to re-open the file. Will fail.

f << table;

Stream is in failed state after failed open and cannot be written.

f.close();

closes file.

Solution

Only open the file once and check for errors.

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".
}
like image 101
user4581301 Avatar answered Apr 15 '26 03:04

user4581301



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!