Q:

After reading from fstream, why does it seem to need its goodbit clearing before writing to it?

Here is an example to illustrate the question:
// Create/truncate file and save '1'
const string NAME = "example.txt";
fstream file(NAME.c_str(), ios::out | ios::trunc);
file << '1';
file.close();

// Re-open file and output its only line
file.open(NAME.c_str(), ios::in | ios::out | ios::app);
string text;
getline(file, text);
cout << "Read \"" << text << "\"" << endl;
// OUTPUTS: Read "1"

// (Try to) Append '2'
file << '2';
file.seekg(0);
getline(file, text);
cout << "Read \"" << text << "\"" << endl;
// OUTPUTS: Read "1"

// (Try to) Append '3'
file.clear(ios::goodbit); /*** SHOULD IT BE NECESSARY TO CLEAR THIS FLAG? ***/
file << '3';
file.seekg(0);
getline(file, text);
cout << "Read \"" << text << "\"" << endl;
// OUTPUTS: Read "13"

I feel a little uneasy about including a line of code that I don't really understand!
Thanks in advance.

A:

goodbit isn't a bit you can clear, it's the state of not having any error state flag bits set.  In a typical implementation of ios,
struct ios {
  enum iostate {
    goodbit = 0,
    badbit  = 0x1,
    failbit = 0x2,
    eofbit  = 0x4,
  };
};

The reason that you need to clear the error state flags is that after getline the eofbit is set so the << operator has no effect.  You can verify this by printing out the error state:
cout << file.rdstate();

