Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!newsfeed.fsmpi.rwth-aachen.de!newsfeed.straub-nv.de!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: fread a file of unknown size Date: Sun, 08 Mar 2015 12:48:48 -0700 Organization: None to speak of Lines: 30 Message-ID: <8761ab46e7.fsf@kst-u.example.com> References: Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="c77ff4d35e33d1c939d3461ebde8dd0d"; logging-data="30823"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX195o/blaGKk0A1ESYRxsV8a" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux) Cancel-Lock: sha1:aSdF1Z65omPAe/hNzxgDafNcmew= sha1:DYLAPssoQrcONaaXDk8tYdWTa6s= Xref: csiph.com comp.lang.c:58000 ruben safir writes: > if you use fread to read a file of unknown size with a set buffer size > of say 500 bytes, when you get to the end of the file you are likely to > read a stub of 500 bytes of info and the eof marker. > > And fread will not red that block and set and oef that can be read with > feof. That is how I understand thinga. So we can either use fseek to > discover the file size and fread accordingly or use fstat? > > is this the proper approach? You've already gotten some good answers. One more thing: Don't use the feof() function to decide when to stop reading. Use the result returned by whatever function you're using to read from the file (fread() in your case). feof() returns the value of the end-of-file flag for the file. That flag is set *after* you attempt to read past the end of the file -- and it's not set if there was an error (that sets the error flag, which you can query with ferror()). So if there's an error reading from the file, just calling feof() won't detect it, and you can have an infinite loop. You can use feof() and/or ferror() *after* reaching the end of the file to find out why there was no more input. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"