
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Size of a File in C
The size of a file refers to the number of bytes it occupies in memory. In C, size of a file can be found by moving the file pointer to the end of the file and checking its position. The position indicates the number of bytes the file contains.
The most common way to do this is by using two functions: fseek() (to move to the end) and ftell() (to get the current position, which is the size of the file).
Syntax
Following is the syntax is as follows:
FILE *fp = fopen("file.txt", "rb"); fseek(fp, 0, SEEK_END); long size = ftell(fp);
Finding File Size with fseek() and ftell()
The fseek() function seeks the file pointer to a specific position and ftell() function returns the current position of the file pointer. In this approach, we will use the both methods.
Consider the below example, where we are opening a file and moving the pointer to the end to find its size using ftell() and print the total number of bytes in the file.
#include<stdio.h> int main() { FILE *file = fopen("file1.txt", "rb"); if (file == NULL) { printf("Cannot open file.\n"); return 1; } fseek(file, 0, SEEK_END); long size = ftell(file); fclose(file); printf("File size: %ld bytes\n", size); return 0; }
If the file opens, the output will be as:
File size: 256 bytes
If the file doesn't open, the output will be as:
Cannot open file.
Finding Size of a Binary File
Here, we are going to find the size of a binary using the same approach, we used above. Consider this example,where we are opening a file named 'data.bin' and using the fseek() to move the pointer to the end, and later 'ftell()' to print the file's size in bytes.
#include<stdio.h> int main() { FILE *file = fopen("data.bin", "rb"); if (!file) { printf("Failed to open file.\n"); return 1; } fseek(file, 0, SEEK_END); long size = ftell(file); fclose(file); printf("Size of data.bin is %ld bytes\n", size); return 0; }
If the file opens, the output will be as:
Size of data.bin is 1024 bytes
If the file doesn't open, the output will be as:
Failed to open file.