1FILE *fp = fopen("example.txt", "r");
2fseek(fp, 0L, SEEK_END);
3int size = ftell(fp);
1If you have the file stream (FILE * f):
2
3fseek(f, 0, SEEK_END); // seek to end of file
4size = ftell(f); // get current file pointer
5fseek(f, 0, SEEK_SET); // seek back to beginning of file
6// proceed with allocating memory and reading the file
7
8Or,
9
10#include <sys/types.h>
11#include <sys/stat.h>
12#include <unistd.h>
13fd = fileno(f);
14struct stat buf;
15fstat(fd, &buf);
16int size = buf.st_size;
17
18Or, use stat, if you know the filename:
19
20#include <sys/stat.h>
21struct stat st;
22stat(filename, &st);
23size = st.st_size;
1If you use :
2
3/**
4 Pay attention to return type!
5 ftell returns long, which can only be used for files under 2GB.
6**/
7fseek(f, 0, SEEK_END); // seek to end of file
8size = ftell(f); // get current file pointer
9fseek(f, 0, SEEK_SET); // seek back to beginning of file
10
11// If u want to get file of large size, use stat() instead
12struct stat buf;
13if(stat(filename, &buf) == -1){
14 return -1;
15}
16return (ssize_t)buf.st_size;