fseek
is the portable answer. In any sane implementation, it will read the file's metadata, rather than its content, to determine the end of the file, while refusing to seek in a stream that is not backed by a filesystem that records such data.
There's no other reliable way to get a file's size in pure ISO C than to seek till the end and then rewind; operating systems have specific APIs to do this, e.g. on a POSIX system you can use fstat
on the fileno
of the FILE*
to get the size:
#include <sys/types.h>
#include <sys/stat.h>
off_t filesize(FILE *fp)
{
// error checking omitted for clarity
int fd = fileno(fp);
struct stat sb;
fstat(fd, &sb);
return sb.st_size;
}