How to get filesize using stat() in C/C++

Problem:

You want to use stat() from sys/stat.h POSIX header in order to get the size of a file.

Solution:

Use this function:

#include <sys/stat.h>

/**
 * Get the size of a file.
 * @return The filesize, or 0 if the file does not exist.
 */
size_t getFilesize(const char* filename) {
    struct stat st;
    if(stat(filename, &st) != 0) {
        return 0;
    }
    return st.st_size;   
}

If you want to use C++ std::string for the filename instead of char*, you can use this equivalent instead:

#include <sys/stat.h>

/**
 * Get the size of a file.
 * @param filename The name of the file to check size for
 * @return The filesize, or 0 if the file does not exist.
 */
size_t getFilesize(const std::string& filename) {
    struct stat st;
    if(stat(filename.c_str(), &st) != 0) {
        return 0;
    }
    return st.st_size;   
}

These functions return exactly the same number as if du -sb would be executed on the same file.

For a detailed stat() reference, see the Opengroup page on mkdir