cfileiofilesize

How do you determine the size of a file in C?


How can I figure out the size of a file, in bytes?

#include <stdio.h>

unsigned int fsize(char* file){
  //what goes here?
}

Solution

  • On Unix-like systems, you can use POSIX system calls: stat on a path, or fstat on an already-open file descriptor (POSIX man page, Linux man page).
    (Get a file descriptor from open(2), or fileno(FILE*) on a stdio stream).

    Based on NilObject's code:

    #include <sys/stat.h>
    #include <sys/types.h>
    
    off_t fsize(const char *filename) {
        struct stat st; 
    
        if (stat(filename, &st) == 0)
            return st.st_size;
    
        return -1; 
    }
    

    Changes:

    If you want fsize() to print a message on error, you can use this:

    #include <sys/stat.h>
    #include <sys/types.h>
    #include <string.h>
    #include <stdio.h>
    #include <errno.h>
    
    off_t fsize(const char *filename) {
        struct stat st;
    
        if (stat(filename, &st) == 0)
            return st.st_size;
    
        fprintf(stderr, "Cannot determine size of %s: %s\n",
                filename, strerror(errno));
    
        return -1;
    }
    

    On 32-bit systems you should compile this with the option -D_FILE_OFFSET_BITS=64, otherwise off_t will only hold values up to 2 GB. See the "Using LFS" section of Large File Support in Linux for details.