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:

#```cpp {filename=“get_filesize_stat.cpp”} #include <sys/stat.h>

/**

example.txt

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

#```cpp {filename="get_filesize_stat_string.cpp"}
#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


Check out similar posts by category: C/C++