C Interview Questions and Answers


How can I find out the size of a file, prior to reading it in?

If the ``size of a file'' is the number of characters you'll be able
to read from it in C (or which were written to it by a previous program), it can
be difficult or impossible to determine this number exactly (other than by reading
the whole file).

Under Unix, the stat call (specifically, the st_size field of the stat structure)
will give you an exact answer.Several other systems supply a Unix-like stat call,
but the sizes reported for text files may be approximate (due to differing end-of-line
representations; . You can open the file and use fstat, or fseek to the end of the
file and then use ftell, but these tend to have the same problems: fstat is not
portable, and generally tells you the same thing stat tells you; ftell is not guaranteed
to return a byte count except for binary files (but, strictly speaking, binary files
don't necessarily support fseek to SEEK_END at all). Some systems provide functions
called filesize or filelength, but these are obviously not portable, either.

Are you sure you have to determine the file's size in advance? Since the most
accurate way of determining the size of a file as a C program will see it is to
open the file and read it, perhaps you can rearrange the code to learn the size
as it reads. (In general, your program should behave gracefully if the number of
characters actually read does not match prior expectations, since any advance determination
of the size might be approximate.)

Posted by:Richards