Question

Is there a way to get the size of a file in C without actually reading the file? I know about fseek but as that sets the 'cursor" to the very end of the file, I'm guessing that does actually read through all of the file.

Am I wrong making this conclusion? Is there a way to do it?

Was it helpful?

Solution

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;
}

OTHER TIPS

I know about fseek but as that sets the 'cursor" to the very end of the file, I'm guessing that does actually read through all of the file.

It does not. For linux, it uses the llseek file operation which will check that the operand is in-range and only set this file descriptor's offset if that check passes. It may need to access the underlying device in order to walk some of the filesystem's data structures, though. But it won't "read" the file in that the operation shouldn't become significantly more expensive with larger files. Technically, that's filesystem-dependent behavior though.

For posix, you could do the following:

get_filesize.h:

#include <stdint.h>

uint64_t get_size(const char *filename);

get_filesize_posix.c:

#include "get_filesize.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

uint64_t get_size(const char *filename)
{
    struct stat s;
    int ret = stat(filename, &s);
    if (ret != 0)
        perror("stat");

    return (uint64_t) s.st_size;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top