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;
1// C program to find the size of file
2#include <stdio.h>
3
4long int findSize(char file_name[])
5{
6 // opening the file in read mode
7 FILE* fp = fopen(file_name, "r");
8
9 // checking if the file exist or not
10 if (fp == NULL) {
11 printf("File Not Found!\n");
12 return -1;
13 }
14
15 fseek(fp, 0L, SEEK_END);
16
17 // calculating the size of the file
18 long int res = ftell(fp);
19
20 // closing the file
21 fclose(fp);
22
23 return res;
24}
25
26// Driver code
27int main()
28{
29 char file_name[] = { "a.txt" };
30 long int res = findSize(file_name);
31 if (res != -1)
32 printf("Size of the file is %ld bytes \n", res);
33 return 0;
34}
35