c file size code example

Example 1: how to check the size of a file c

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 
#include 
#include 
fd = fileno(f); 
struct stat buf;
fstat(fd, &buf);
int size = buf.st_size;

Or, use stat, if you know the filename:

#include 
struct stat st;
stat(filename, &st);
size = st.st_size;

Example 2: c get file size

FILE *fp = fopen("example.txt", "r");
fseek(fp, 0L, SEEK_END);
int size = ftell(fp);

Example 3: c file size

If you use :

/** 
	Pay attention to return type! 
	ftell returns long, which can only be used for files under 2GB. 
**/
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

// If u want to get file of large size, use stat() instead
struct stat buf;
if(stat(filename, &buf) == -1){
   return -1;
}
return (ssize_t)buf.st_size;

Tags:

Misc Example