fstream object and good() and while block

Input/Output with files
http://www.cplusplus.com/doc/tutorial/files/

My txt file:
example555.txt and its contents:
TestText 1
TestText B
TestText 555 666

Why do we not need the first while?

My code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// fstream read write file

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main ()
{
  // writing to file
  fstream myfile("example555.txt",ios::out|ios::app);
  if (myfile.is_open())
  {
    // why does it collapse here: it continuously writes into the .txt
    // without while it looks working good
    while ( myfile.good() ) 
    {
       myfile<<"This new line has been appended to the end of the file."<<endl;
    }
    myfile.close();
  }

  else { cout << "Unable to open file for reading!"; }

  // reading from file
  string line;
  myfile.open("example555.txt",ios::in);

  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }

  else { cout << "Unable to open file for writing!"; }


  return 0;
}


The file will always be good while writing to it, unless you some how run out of space etc, lol.

Maybe use a for-loop. So long as you know how many times you'll need to repeat something to the file, a for-loop would be best.
Lynx876, thanks.

I may see it now.

reading file --> file has an end where good() returns false

writing file --> file has not an end, we can always write (append) to it --> good() is always true (until no more space left) :) yeessssss

This is not good practice:
25
26
27
28
29
30
31
32
33
34
35
36
37
  // reading from file
  string line;
  myfile.open("example555.txt",ios::in);

  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }
Notice at line 33 the file is read from, using getline().
The read may fail or succeed.
Then at line 34 the line is displayed (even though we haven't checked that the getline was succcessful).
After that, the while loop condition myfile.good() is tested.
This in colloquial language, is bolting the stable door after the horse has fled.

Do this instead:
1
2
3
4
5
6
7
8
9
10
11
12
13
    // reading from file
    string line;
    myfile.open("example555.txt",ios::in);

    if (myfile.is_open())
    {
        while ( getline(myfile,line) )
        {
            cout << line << endl;
        }

        myfile.close();
    }
Last edited on
Hi, Chervil. Thanks for pointing out to that

getline has a bool like return value.

Somehow I haven't thought of this so far. :)

http://stackoverflow.com/questions/4708335/istreamgetline-return-type
Last edited on
Topic archived. No new replies allowed.