Question 19.12

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, it is difficult or impossible to determine this number exactly).

Under Unix, the stat call will give you an exact answer. Several other systems supply a Unix-like stat which will give an approximate answer. You can fseek to the end 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. Some systems provide routines called filesize or filelength, but these are 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.

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


Read sequentially: prev next up top


This page by Steve Summit // Copyright 1995 // mail feedback