On a POSIX system, you can use stat .
Summary:
#include <sys/stat.h> int stat(const char *restrict path, struct stat *restrict buf);
So, you declare a stat structure to store the result and pass a pointer to stat:
struct stat buf; stat(filename, &buf);
The size (in bytes) is contained in buf.st_size .
If your standard library implementation includes <experimental/filesystem> (which should exit experimental with C ++ 17), you can use it instead. #include <experimental/filesystem> , and then use std::experimental::filesystem::file_size(filename) instead of your filesize function. (This also returns the size in bytes. It simply calls the stat function on POSIX systems.)
For GCC, you will need to set the -lstdc++fs link (see file system linker filter error ).
source share