C Program to find size of a File
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; } |
chevron_right
filter_none
Recommended Posts:
- C program to find the size of int, float, double and char
- C program to copy contents of one file to another file
- C program for file Transfer using UDP
- C program to delete a file
- C++ program to create a file
- LEX program to add line numbers to a given file
- Lex program to search a word in a file
- C Program to print contents of file
- C++ program to print unique words in a file
- C Program to merge contents of two files into a third file
- C Program to count number of lines in a file
- C++ program to append content of one text file to another
- C Program to count the Number of Characters in a File
- Write a C program that displays contents of a given file like 'more' utility in Linux
- C Program for Lower Case to Uppercase and vice-versa in a file
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



