how to find the size of a file in C 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);
size = ftell(f);
fseek(f, 0, SEEK_SET);
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;
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 :
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, 0, SEEK_SET);
struct stat buf;
if(stat(filename, &buf) == -1){
return -1;
}
return (ssize_t)buf.st_size;
Example 4: size of file in c
#include <stdio.h>
long int findSize(char file_name[])
{
FILE* fp = fopen(file_name, "r");
if (fp == NULL) {
printf("File Not Found!\n");
return -1;
}
fseek(fp, 0L, SEEK_END);
long int res = ftell(fp);
fclose(fp);
return res;
}
int main()
{
char file_name[] = { "a.txt" };
long int res = findSize(file_name);
if (res != -1)
printf("Size of the file is %ld bytes \n", res);
return 0;
}