How can I get a file's size in C? [duplicate]
Using standard library:
Assuming that your implementation meaningfully supports SEEK_END:
fseek(f, 0, SEEK_END); // seek to end of filesize = ftell(f); // get current file pointerfseek(f, 0, SEEK_SET); // seek back to beginning of file// proceed with allocating memory and reading the file
Linux/POSIX:
You can use stat
(if you know the filename), or fstat
(if you have the file descriptor).
Here is an example for stat:
#include <sys/stat.h>struct stat st;stat(filename, &st);size = st.st_size;
Win32:
You can use GetFileSize or GetFileSizeEx.
If you have the file descriptor fstat()
returns a stat structure which contain the file size.
#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>// fd = fileno(f); //if you have a stream (e.g. from fopen), not a file descriptor.struct stat buf;fstat(fd, &buf);off_t size = buf.st_size;