determine last line of file entries

Discussion in 'C' started by magix, Sep 30, 2006.

  1. magix

    magix New Member

    Joined:
    Sep 30, 2006
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Hi,

    when I read entries in file i.e text file, how can I determine the first line and the last line ?
    I know the first line of entry can be filtered using counter, but how about the last line of entry in EOF while loop ?

    while (! file.eof() )
    {
    ....
     
  2. Bill Pursell

    Bill Pursell New Member

    Joined:
    Nov 29, 2006
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    You should not ever write:

    while (! file.eof() ) { ... }

    Suppose you have a file with 10 characters,
    and you write:

    while (! eof(file)) { fread(buf, 1, 10, file); ...}

    You will go through the loop twice--on the
    first loop, buf will contain the contents of
    the file after fread returns. (Assuming no
    errors.) When you return to the top of
    the loop, eof() will return 0. You then call
    fread, which will return 0, and buf still contains
    the contents of the file and the loop is
    processed. Then eof() returns true.

    ie, eof() doesn't return true until you've
    actually read an eof, which doesn't happen
    until you attempt to read more data than
    is available.

    You should construct your loop as
    while ( fread(buf, sizeof *buf, 1, file) == 1) {
    ...
    }
     
  3. magix

    magix New Member

    Joined:
    Sep 30, 2006
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    I got the answer from other forum but I am definitely looking forward to this exiting forum and have lots of questions as I am starting off with the programming.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice