prev up next   top/contents search

comp.lang.c FAQ list · Question 19.12

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

A: 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. [footnote] 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; see question 12.40). 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.) See also questions 7.29, 7.30, and 20.2.

Additional links: further reading

References: ISO Sec.
H&S Sec. 15.5.1
PCS Sec. 12 p. 213
POSIX Sec. 5.6.2

prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North