The Wayback Machine - https://web.archive.org/web/20240118170209/https://www.geeksforgeeks.org/c-program-find-size-file/
Open In App
Related Articles

C Program to find size of a File

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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.




// C program to find the size of file
#include <stdio.h>
  
long int findSize(char file_name[])
{
    // opening the file in read mode
    FILE* fp = fopen(file_name, "r");
  
    // checking if the file exist or not
    if (fp == NULL) {
        printf("File Not Found!\n");
        return -1;
    }
  
    fseek(fp, 0L, SEEK_END);
  
    // calculating the size of the file
    long int res = ftell(fp);
  
    // closing the file
    fclose(fp);
  
    return res;
}
  
// Driver code
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;
}


Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 28 Apr, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads