C Program to find size of a File
Last Updated :
28 Apr, 2018
Given a text file, find its size in bytes.
Examples:
Input : file_name = "a.txt"
Let "a.txt" contains "geeks"
Output : 6 Bytes
There are 5 bytes for 5 characters then an extra
byte for end of file.
Input : file_name = "a.txt"
Let "a.txt" contains "geeks for geeks"
Output : 16 Bytes
The idea is to use fseek() in C and ftell in C. Using fseek(), we move file pointer to end, then using ftell(), we find its position which is actually size in bytes.
#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;
}
|
Share your thoughts in the comments
Please Login to comment...