Thread: fstream help, sorry

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    10

    fstream help, sorry

    Sorry if this is wasting your time, but I have no idea how to exactly use the .eof() in a while loop. I'm getting really frustrated not being able to find the right way. Help if you can or want, thanks you so very much in advance!

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Use it to test if you've reached EOF. Do NOT, however, use it as a loop condition unless you know what you're doing.

  3. #3
    Registered User
    Join Date
    May 2008
    Posts
    10
    k, thanks

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Don't use it at all. It is better to loop until the read fails.

    Code:
    while (read data into your variable)
    {
        use variable here
    }
    Using eof at all has problems (other than to check to see if you attempted to read past the end of the file, which is mostly useless). It's possible for the read to succeed and eof to still be set, which would mean you fail to process your last piece of data. It's possible for a read to fail and the eof() to not be set, in which case you could process a piece of data twice or go into an infinite loop.

  5. #5
    Registered User
    Join Date
    Jun 2008
    Posts
    5
    what about .good()

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    good() is better than eof() and is the same as checking the return value of the read operation, but it is harder to use. If you put the read into the while control, then you handle everything right there and the loop ends as soon as the read fails. If you check good(), then you have to do the read, then use an if statement with good() to see if you need to break out of the loop. It is not as clean.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems with fstream, one variabile for write and read
    By Smjert in forum C++ Programming
    Replies: 3
    Last Post: 02-03-2009, 10:19 PM
  2. Fstream. I/O
    By kevinawad in forum C++ Programming
    Replies: 2
    Last Post: 07-07-2008, 09:19 AM
  3. ARGH! fstream errors
    By OttoDestruct in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2004, 10:37 PM
  4. Are fstream and ofstream incompatible?
    By johnnyd in forum C++ Programming
    Replies: 5
    Last Post: 03-19-2003, 12:21 PM
  5. Problems with fstreams.
    By mosdef in forum C++ Programming
    Replies: 7
    Last Post: 06-19-2002, 03:36 PM

Tags for this Thread