C Program to find size of a File

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

FILE *fp = fopen("filename", "rb");
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fclose(fp);

Method 1: Finding File Size with fseek() and ftell()

The fseek() function moves the file pointer to a specific position and ftell() function returns the current position of the file pointer. By seeking to the end and getting the position, we can determine the file size −

#include <stdio.h>

int main() {
    FILE *file = fopen("sample.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;
}
File size: 256 bytes

Method 2: Finding Size of Binary File

The same approach works for binary files. Here we demonstrate reading a binary file and calculating its size −

#include <stdio.h>

int main() {
    FILE *file = fopen("data.bin", "rb");
    if (file == NULL) {
        printf("Failed to open binary file.\n");
        return 1;
    }
    
    fseek(file, 0, SEEK_END);
    long size = ftell(file);
    fclose(file);
    
    printf("Binary file size: %ld bytes\n", size);
    return 0;
}
Binary file size: 1024 bytes

Key Points

  • Always use "rb" mode for accurate byte counting, especially for binary files.
  • Check if file opens successfully before attempting to read its size.
  • Remember to close the file using fclose() after operations.
  • The ftell() function returns -1 on error.

Conclusion

Finding file size in C using fseek() and ftell() is a reliable method that works for both text and binary files. Always ensure proper error checking when working with file operations.

Revathi Satya Kondra
Revathi Satya Kondra

Technical Content Writer, Tutorialspoint

Updated on: 2026-03-15T10:11:28+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements