How to find an end of file

Discussion in 'C Programming' started by junky_fellow, Dec 8, 2004.

  1. junky_fellow

    junky_fellow Guest

    What is the proper way of finding an end of file condition while reading
    a file ?

    How does feof() detects that end of file is reached ?
    Does this require support from OS ?

    Thanx in advance for any help ...
    junky_fellow, Dec 8, 2004
    #1
    1. Advertising

  2. "junky_fellow" <> wrote in message
    news:...
    > What is the proper way of finding an end of file condition while reading
    > a file ?
    >
    > How does feof() detects that end of file is reached ?


    feof() does not detect that end of file is reached, it reports that end of file
    was reached during a previous read operation.

    > Does this require support from OS ?


    if files are implemented with the OS, feof() will rely on the OS reporting such
    a condition for read operations.
    if files are implemented within the C library, the OS is not an issue.

    It is important to notice that feof() is counterintuitive:
    - Whether a read operation that reaches the end of a file set the condition is
    not specified : fgets() reading the last line will probably not set it, while
    fscanf() eating trailing white space might.
    - If the file is being written by another function (or process where that makes
    sense), feof() may return non 0 even after more data becomes available for
    reading (clearerr() or fseek() may be needed before reading).

    As a rule of thumb, only use feof() to disambiguate end of file from read error
    after a read operation fails.
    Idioms such as while (!feof(f)) { ... } and do { ... } while (!feof(f)); are
    bogus and must be avoided.

    --
    Chqrlie.

    PS: I know about 7.19.6.2 example 3 verse 19. This code snipplet is bogus and
    useless. AAMOF most do/while loops are bogus anyway.
    Charlie Gordon, Dec 8, 2004
    #2
    1. Advertising

  3. junky_fellow wrote:
    > What is the proper way of finding an end of file condition while reading
    > a file ?
    >
    > How does feof() detects that end of file is reached ?
    > Does this require support from OS ?


    You can do it yourself without feof(), by doing

    struct stat statstruct;

    stat("filename", &statstruct);

    statstruct.st_size is the number of bytes in the file.

    > Thanx in advance for any help ...


    Using feof() is easier though.

    FILE *fp = fopen(...);

    while (!feof(fp)) {
    ... read stuff
    }
    Johnathan Doe, Dec 8, 2004
    #3
  4. > Using feof() is easier though.
    >
    > FILE *fp = fopen(...);
    >
    > while (!feof(fp)) {
    > ... read stuff
    > }


    And of course as the previous poster said, you may have a short count or
    even an error, so take that into account.

    while (!feof(fp)) {

    /* Short count ? */
    n = fread(buffer, ..., fp);

    if (n != whatever) {
    if (ferror())
    ... some kind of error
    if (feof())
    ... end of file
    }
    }
    Johnathan Doe, Dec 8, 2004
    #4
  5. Johnathan Doe <No-spam-here-johnathan_doe@!!!nospamthanks!!!fastmail.com.au> scribbled the following:
    > junky_fellow wrote:
    >> What is the proper way of finding an end of file condition while reading
    >> a file ?
    >>
    >> How does feof() detects that end of file is reached ?
    >> Does this require support from OS ?


    > You can do it yourself without feof(), by doing


    > struct stat statstruct;


    > stat("filename", &statstruct);


    > statstruct.st_size is the number of bytes in the file.


    No you can't. There is no struct stat or stat() in the C language.

    --
    /-- Joona Palaste () ------------- Finland --------\
    \-------------------------------------------------------- rules! --------/
    "You have moved your mouse, for these changes to take effect you must shut down
    and restart your computer. Do you want to restart your computer now?"
    - Karri Kalpio
    Joona I Palaste, Dec 8, 2004
    #5
  6. "Johnathan Doe" <No-spam-here-johnathan_doe@!!!NOSPAMTHANKS!!!fastmail.com.au>
    wrote in message
    news:41b6c124$0$25761$...
    > > Using feof() is easier though.
    > >
    > > FILE *fp = fopen(...);
    > >
    > > while (!feof(fp)) {
    > > ... read stuff
    > > }

    >
    > And of course as the previous poster said, you may have a short count or
    > even an error, so take that into account.


    The previous poster said to avoid this stupid bogus idiom !

    > while (!feof(fp)) {
    >
    > /* Short count ? */
    > n = fread(buffer, ..., fp);
    >
    > if (n != whatever) {
    > if (ferror())
    > ... some kind of error
    > if (feof())
    > ... end of file
    > }
    > }


    Instead do this :

    for (;;) {
    n = fread(buffer, sizeof(type), count, fp);
    if (n != count) {
    ... handle partial read.
    if (ferror(f)) {
    ... handle error and break or return
    break;
    }
    if (feof(f)) {
    .. handle end of file and break or return
    break;
    }
    } else {
    ... handle normal read
    }
    }

    --
    Chqrlie.
    Charlie Gordon, Dec 8, 2004
    #6
  7. Joona I Palaste wrote:
    > No you can't. There is no struct stat or stat() in the C language.


    Assuming you're working on 99% of OSes out there, yes you can.
    Johnathan Doe, Dec 8, 2004
    #7
  8. Johnathan Doe <No-spam-here-johnathan_doe@!!!nospamthanks!!!fastmail.com.au> scribbled the following:
    > Joona I Palaste wrote:
    >> No you can't. There is no struct stat or stat() in the C language.


    > Assuming you're working on 99% of OSes out there, yes you can.


    Here we discuss 100% of the OSes out there.

    --
    /-- Joona Palaste () ------------- Finland --------\
    \-------------------------------------------------------- rules! --------/
    "A computer program does what you tell it to do, not what you want it to do."
    - Anon
    Joona I Palaste, Dec 8, 2004
    #8
  9. junky_fellow

    CBFalconer Guest

    Johnathan Doe wrote:
    >
    > Joona I Palaste wrote:
    > > No you can't. There is no struct stat or stat() in the C language.

    >
    > Assuming you're working on 99% of OSes out there, yes you can.


    Read the welcome message. This group deals with the language as
    defined by the ISO standards, not some imaginary uncontrolled
    offshoot. Reference to non-standard features is off-topic. Also
    use of feof for any purpose other than to disambiguae a read error
    is almost always an error. You would know all this is you had
    bothered to read this group for a period before breaking in with
    misinformation.

    --
    Chuck F () ()
    Available for consulting/temporary embedded and systems.
    <http://cbfalconer.home.att.net> USE worldnet address!
    CBFalconer, Dec 8, 2004
    #9
  10. junky_fellow

    MarcSmith Guest

    cuz he is using a file pointer can he seek using fseek to the end of th
    file, and use ftell to tell him the filesize.

    for example:
    i assume cuz he is using fgets, feof...ftell and fseek are defined. o
    they should be defined.


    Code
    -------------------


    long filesize( FILE *fp )
    {
    if (fp==NULL) return 0L;
    fseek( fp, 0, SEEK_END );
    return ftell(fp);
    }

    -------------------


    -
    MarcSmit
    -----------------------------------------------------------------------
    Posted via http://www.codecomments.co
    -----------------------------------------------------------------------
    MarcSmith, Dec 8, 2004
    #10
  11. On Wed, 08 Dec 2004 20:44:56 +1100, in comp.lang.c , Johnathan Doe
    <No-spam-here-johnathan_doe@!!!NOSPAMTHANKS!!!fastmail.com.au> wrote:

    >Joona I Palaste wrote:
    >> No you can't. There is no struct stat or stat() in the C language.

    >
    >Assuming you're working on 99% of OSes out there, yes you can.


    Please read the C Standard and point out where stat() is defined.

    What 99% of OSen (sure about that number? AmigaOS, Atari TOS, CPM, VMS4.x,
    VM/CMS, MacOS 8.1, DOS3.11, Embedded XP ? I have no clue, I bet you don't
    either) support is neither here nor there.

    --
    Mark McIntyre
    CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
    CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

    ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
    http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
    ----= East and West-Coast Server Farms - Total Privacy via Encryption =----
    Mark McIntyre, Dec 8, 2004
    #11
  12. On Wed, 8 Dec 2004 15:26:47 -0600, MarcSmith
    <> wrote:


    >
    >cuz he is using a file pointer can he seek using fseek to the end of the
    >file, and use ftell to tell him the filesize.


    Oh, bad news.

    7.19.9.4 The ftell function

    ....For a text stream, its file position indicator contains unspecified
    information, usable by the fseek function for returning the file position
    indicator for the stream to its position at the time of the ftell call;
    the difference between two such return values is not necessarily a
    meaningful measure of the number of characters written or read.


    Oh, and what if the stream is a pipe?

    Thank you for playing. For an additional two-fifty, we can send you the
    consolation prize.


    --
    #include <standard.disclaimer>
    _
    Kevin D Quitt USA 91387-4454 96.37% of all statistics are made up
    Per the FCA, this address may not be added to any commercial mail list
    Kevin D. Quitt, Dec 8, 2004
    #12
  13. junky_fellow

    Chris Torek Guest

    In article <>
    junky_fellow <> wrote:
    >What is the proper way of finding an end of file condition while reading
    >a file ?


    Try to read the file, and if it fails, see if the reason it failed
    was "end of file".

    >How does feof() detects that end of file is reached ?


    It does not. It answers a question about "why that earlier failure?"
    for a previous read that you already know failed. The two possible
    reasons allowed, in Standard C (and in the Unix-like systems on
    which C was developed), are "the attempt to read failed because
    there was nothing more to read, i.e., a perfectly ordinary end-of-file
    occurred" and "the attempt to read failed because of some sort of
    underlying failure, such as hitting a bad spot on the disk, or the
    hardware is on fire." The "no more data" case causes feof(fp) to
    become nonzero, while the "hardware failure/disk drive has melted"
    case causes ferror(fp) to become true.

    >Does this require support from OS ?


    It requires only the ability to report failures when reading files,
    and to distinguish between "no more data" and "hardware error".

    Note that C streams can be connected to interactive devices (like
    human beings typing at keyboards, or Internet connections, on
    systems that support such things), and it is not possible to predict
    in advance just when a human being or Internet connection will
    reach "end of input". But there is no need for prescience: if you
    want more input, just ask for it, and when you no longer get it,
    only *then* do you need to find out why. Sure, it might be nice
    sometimes to predict in advance how much input you will get -- but
    in the worst case, you can just copy everything to a temporary
    file, and then use the copy. This even works on human beings and
    Internet connections.
    --
    In-Real-Life: Chris Torek, Wind River Systems
    Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
    email: forget about it http://web.torek.net/torek/index.html
    Reading email is like searching for food in the garbage, thanks to spammers.
    Chris Torek, Dec 9, 2004
    #13
  14. junky_fellow

    MarcSmith Guest

    i believe that even using pipes at least in dos it does give filesize o
    a given file since it is a given file he is talking about.

    program <infile.dat // for example, does give filesize

    but of course, stdin by itself does not


    -
    MarcSmit
    -----------------------------------------------------------------------
    Posted via http://www.codecomments.co
    -----------------------------------------------------------------------
    MarcSmith, Dec 9, 2004
    #14
  15. MarcSmith <> writes:
    > i believe that even using pipes at least in dos it does give filesize of
    > a given file since it is a given file he is talking about.
    >
    > program <infile.dat // for example, does give filesize
    >
    > but of course, stdin by itself does not.


    <OT>
    That's not a pipe.
    </OT>

    --
    Keith Thompson (The_Other_Keith) <http://www.ghoti.net/~kst>
    San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
    We must do something. This is something. Therefore, we must do this.
    Keith Thompson, Dec 9, 2004
    #15
  16. junky_fellow

    MarcSmith Guest

    1. maybe the person can post with compiler and environment like wht o
    he/she is using. or specify what he/she is doing more specifically.

    2. when someone refers to 90% of the oses out there, i make a bet tha
    i lost track of what percentage Microsoft owns in market share relativ
    to operating systems, but i make a bet it is more close to 80%. th
    other notion is what is the remaining percentage, that could be linu
    or unix installations or PowerPc, and probably 0.5% market share to th
    remaining oses. are you still using them? as a software developer,
    program for the masses, which basically falls in dos / windows / linu
    / unix installations, and that it is about it. most pc's like the appl
    can run dos or windows programs even the amiga. i seem to agree with th
    other guy about the post. the other percentange isn't worth my time o
    money. stat and fstat are supported by a lot of compilers for thos
    platforms. this website is trying the make everybody happy on al
    systems no matters what c or c++ compiler you are using just so it i
    ansi or iso based. i think that you have a tough job ahead of you
    trying to make everybody happy. that's all...enough said


    -
    MarcSmit
    -----------------------------------------------------------------------
    Posted via http://www.codecomments.co
    -----------------------------------------------------------------------
    MarcSmith, Dec 10, 2004
    #16
  17. junky_fellow

    Guest

    You said that on Unix like system, the attempt to read may fail due to
    two reasons: 1) Some Error Condition 2) end-of-file occurred.

    Don't you feel that if read fails( the number of bytes read are less
    than requested), we should first check for error.
    If there's no error, that means the end-of-file has reached. I mean
    to say there is no need for feof().
    , Dec 10, 2004
    #17
  18. junky_fellow

    Chris Torek Guest

    In article <>
    <> wrote:
    >You said that on Unix like system, the attempt to read may fail due to
    >two reasons: 1) Some Error Condition 2) end-of-file occurred.
    >
    >Don't you feel that if read fails( the number of bytes read are less
    >than requested), we should first check for error.
    >If there's no error, that means the end-of-file has reached. I mean
    >to say there is no need for feof().


    The Unix-specific details are off topic (though I will note that
    if you request, e.g., 100 bytes and get 12, that is not a "failure"
    on a POSIX system) -- but the way the underlying OS-level read
    fails feeds in turn into the feof() and ferror() functions in C.
    That is, feof(fp) tells you "an earlier OS-level read failed to
    get anything due to reaching end of file", while ferror(fp) tells
    you "an earlier OS-level read failed to get anything due to
    I/O-error."

    Because the OS-level request has already failed, the standard I/O
    subsystem in the C library must *record* the reason somewhere, if
    it is to let you ask about it after-the-fact like this. The place(s)
    it records the reason(s) are secret (however poorly-kept that secret
    is -- if you examine the system, you can find it easily), but feof()
    and ferror() interrogate this recorded information.
    --
    In-Real-Life: Chris Torek, Wind River Systems
    Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
    email: forget about it http://web.torek.net/torek/index.html
    Reading email is like searching for food in the garbage, thanks to spammers.
    Chris Torek, Dec 10, 2004
    #18
  19. junky_fellow

    CBFalconer Guest

    MarcSmith wrote:
    >
    > 1. maybe the person can post with compiler and environment like wht os
    > he/she is using. or specify what he/she is doing more specifically.


    If anyone needs to specify that he or she is off-topic. c.l.c
    deals with the _portable_ C language only.

    --
    Chuck F () ()
    Available for consulting/temporary embedded and systems.
    <http://cbfalconer.home.att.net> USE worldnet address!
    CBFalconer, Dec 10, 2004
    #19
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jimmy
    Replies:
    3
    Views:
    327
    J. J. Farrell
    Sep 9, 2011
  2. Jimmy
    Replies:
    13
    Views:
    649
    Peter Nilsson
    Sep 21, 2011
  3. Wybo Dekker
    Replies:
    1
    Views:
    350
    Yukihiro Matsumoto
    Nov 15, 2005
  4. vdvorkin
    Replies:
    0
    Views:
    398
    vdvorkin
    Feb 10, 2011
  5. vdvorkin
    Replies:
    3
    Views:
    806
    vdvorkin
    Feb 14, 2011
Loading...

Share This Page