How to get the size of a file in C

How to get a file's size in C?

asked Jan 21, 2013 by anonymous

1 Answer

 
Best answer

If you have the file stream (FILE * f):

fseek(f, 0, SEEK_END); // seek to end of file
size = ftell(f); // get current file pointer
fseek(f, 0, SEEK_SET); // seek back to beginning of file
// proceed with allocating memory and reading the file

Or,

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
fd = fileno(f); 
struct stat buf;
fstat(fd, &buf);
int size = buf.st_size;

Or, use stat, if you know the filename:

#include <sys/stat.h>
struct stat st;
stat(filename, &st);
size = st.st_size;

Of course, check the errors.

answered Jan 21, 2013 by anonymous
edited Feb 4, 2013 by SA

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...