Hmmm, no main() .
FILE *fp;
unsigned long count;
Is a file size certain to fit within an unsigned long?
Answer: NO.
For example, SGI IRIX programs compiled in either
32 bit mode have 32 bit unsigned long, but the SGI XFS filesystem
supports individual files up to about 10 terabytes.
if ((fp = fopen("the file","r")) != NULL) /* fopen() the file */
And if the file isn't readable? The original poster asked how to
portably the file size, but only much much later implied that the
file might be readable.
{
count = 0; /* initialize count to 0 */
while (fgetc(fp) != EOF) ++count; /* until fgetc returns EOF, */
/* add 1 to the counter */
If I recall correctly, on systems that differentiate between
binary and text streams, opening with "r" opens as a text stream.
The number of chars read from a text file could be more or
less than the binary file size. On the other hand, Similarily,
if the file was written as text and is being read as binary, the
"size" isn't going to match either.
Now that I think of it, I don't recall that the standard promises
that a file written as text has any consistant meaning when read
as binary. For example, some systems automatically compress older
text files, and transparently uncompress them when the file is
read back as text -- but because the compressed file must be
manipuable in compressed format, reading the file in binary might
give you the compressed form. In such a system, reading a text file
in binary might give you different answers at different times.
The C standard doesn't care: it's promises are framed in terms
of what is read back in text mode after being written in text mode,
and in terms of what is read back in binary mode after being
written in binary mode.
fclose(fp); /* fclose() the file */
}
What value does count have here if the file was unreadable?
Since count was local to this block, the value of count has
disappeared by here, but you have not returned any value
nor assigned into any result variable that has a lnnger
lifetime. The optimizer thus might decide to throw away
the 'count' variable. Indeed, the only thing stopping the
compiler from optimizing away *everything* is the fact
that "the file" might be a named pipe and so there might
be side effects from having done the read (that and the
fact that in Unix the act of doing the read changes the
"last accessed" time.