Is there any C library function that returns the size of a given file?
Otherwise, is there a way in which file size can be determined in a C
program? I need to get this for both Linux and Windows platforms, so a
generic solution is what I am looking for.
What do you want to use the data for?
*WHICH* "size of a given file"? There are several different definitions,
not all listed here, which are likely to give different answers:
(1) The number of characters you can read with fgetc() from the file
when it is opened in text mode. (On a system with line endings \r\n,
this counts \r\n as one character, but on disk it's two (MS-DOS and
Windows). If the file really contains binary stuff, on some systems
a control-Z is treated as end-of-file and it and the bytes after it
don't count. If you had ideas of reading the whole file into memory
in text mode, this is the size you want.
(2) The number of characters you can read with fgetc() from the file
when it is opened in binary mode. This may count bytes at the
end of the file from the last byte written to the end of a disk block
(e.g. on CP/M, which doesn't track end-of-file to a byte boundary).
If you had ideas of reading the whole file into memory in binary
mode, this is the size you want. It's also likely to be the size
given by "ls -l".
(3) The amount of disk space needed to store the file. This tends to
be the size of the data on disk rounded up to a block boundary.
There are variations on this as to whether to count "indirect"
blocks used to keep track of blocks belonging to the file.
Files with unwritten "holes" can make (3) drastically smaller
than (2) (e.g. the multi-gigabyte file with unwritten holes
that fits on a floppy).
(1) and (2) you can get by opening the file, reading it to the end,
and counting characters. (3) can be obtained by non-standard-C
function stat() on some systems (st_blocks multiplied by the disk
block size). stat() may often give you (2) in st_size also.
Gordon L. Burditt