0
0
CHow-ToBeginner · 3 min read

How to Get File Size in C: Simple and Clear Guide

To get a file size in C, open the file in binary mode with fopen, move the file pointer to the end using fseek, then use ftell to get the position which equals the file size in bytes. Finally, close the file with fclose.
📐

Syntax

Use fopen to open the file, fseek to move the pointer, and ftell to get the size. Then close the file with fclose.

  • FILE *fopen(const char *filename, const char *mode); opens the file.
  • int fseek(FILE *stream, long offset, int whence); moves the file pointer.
  • long ftell(FILE *stream); returns the current position of the file pointer.
  • int fclose(FILE *stream); closes the file.
c
FILE *file = fopen("filename", "rb");
fseek(file, 0, SEEK_END);
long size = ftell(file);
fclose(file);
💻

Example

This example opens a file named example.txt, finds its size in bytes, and prints it.

c
#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "rb");
    if (file == NULL) {
        printf("Failed to open file.\n");
        return 1;
    }

    fseek(file, 0, SEEK_END); // Move to end of file
    long size = ftell(file);  // Get current position (file size)
    fclose(file);

    printf("File size: %ld bytes\n", size);
    return 0;
}
Output
File size: 123 bytes
⚠️

Common Pitfalls

  • Not opening the file in binary mode ("rb") can cause incorrect size on some systems.
  • Forgetting to check if fopen returns NULL leads to errors.
  • Not resetting the file pointer after fseek if you want to read the file later.
  • Using ftell before fseek to the end will not give the file size.
c
// Wrong way:
FILE *file = fopen("example.txt", "r");
long size = ftell(file); // Wrong: pointer is at start, size will be 0

// Right way:
fseek(file, 0, SEEK_END);
long size = ftell(file);
📊

Quick Reference

FunctionPurposeNotes
fopen(filename, mode)Open fileUse "rb" mode for binary files
fseek(file, 0, SEEK_END)Move pointer to endNeeded to find file size
ftell(file)Get current pointer positionReturns file size after fseek to end
fclose(file)Close fileAlways close files to free resources

Key Takeaways

Open the file in binary mode with fopen("filename", "rb") to get accurate size.
Use fseek(file, 0, SEEK_END) to move to the file's end before calling ftell.
ftell(file) returns the file size in bytes after seeking to the end.
Always check if fopen returns NULL to avoid errors.
Close the file with fclose to release system resources.