Finding the size of a file is a common task in C programming. Knowing the file size is useful for memory allocation, file processing, and performance optimization. For example, if you want to read a file into memory, knowing its size helps allocate the exact amount of memory required.
In this tutorial, we will explore different methods to determine the size of a file in C. You will learn to use functions like fseek()
, ftell()
, and stat()
, and handle errors effectively to ensure reliable programs.
Understanding the Problem
The size of a file is the number of bytes it contains. While some functions can directly read the file into memory, it is often necessary to know its size first to allocate the right buffer.
C provides multiple ways to find file size. Using fseek()
and ftell()
lets you determine the size by moving the file pointer to the end and checking its position. Using stat()
provides size and other file metadata. Proper error handling ensures you do not attempt to measure a non-existent or inaccessible file.
Program 1: Using fseek()
and ftell()
This method opens the file in binary mode, moves the file pointer to the end, and measures its position to determine the size.
#include <stdio.h>
int main() {
const char *filename = "data.txt";
FILE *file = fopen(filename, "rb");
if (file == NULL) {
perror("Error opening file");
return 1;
}
fseek(file, 0, SEEK_END);
long size = ftell(file);
fclose(file);
printf("Size of file '%s' is %ld bytes.\n", filename, size);
return 0;
}
In this program, we open the file in binary mode using fopen()
. fseek(file, 0, SEEK_END)
moves the file pointer to the end. ftell(file)
returns the position of the pointer, which corresponds to the file size in bytes. Finally, fclose()
closes the file safely.
Program 2: Using stat()
The stat()
function retrieves file metadata, including its size, without manually moving file pointers.
#include <stdio.h>
#include <sys/stat.h>
int main() {
const char *filename = "data.txt";
struct stat st;
if (stat(filename, &st) != 0) {
perror("Error retrieving file information");
return 1;
}
printf("Size of file '%s' is %lld bytes.\n", filename, (long long)st.st_size);
return 0;
}
Here, stat()
fills the st
structure with file information. st.st_size
contains the file size in bytes. This method is convenient when you also want other file attributes, such as permissions or modification time.
Program 3: Using fread()
and a Loop
You can calculate the file size by reading the file in chunks and counting the total bytes read. This method is useful if you want to process the file at the same time.
#include <stdio.h>
int main() {
const char *filename = "data.txt";
FILE *file = fopen(filename, "rb");
if (file == NULL) {
perror("Error opening file");
return 1;
}
long size = 0;
char buffer[1024];
size_t bytesRead;
while ((bytesRead = fread(buffer, 1, sizeof(buffer), file)) > 0) {
size += bytesRead;
}
fclose(file);
printf("Size of file '%s' is %ld bytes.\n", filename, size);
return 0;
}
Here, the program reads the file in 1 KB chunks until EOF. The total bytes read give the file size. This approach works even if you are processing the file data simultaneously.
Program 4: Using fgetc()
in a Loop
For small files, you can read each character one by one to calculate the size. This is simple but less efficient for large files.
#include <stdio.h>
int main() {
const char *filename = "data.txt";
FILE *file = fopen(filename, "rb");
if (file == NULL) {
perror("Error opening file");
return 1;
}
long size = 0;
while (fgetc(file) != EOF) {
size++;
}
fclose(file);
printf("Size of file '%s' is %ld bytes.\n", filename, size);
return 0;
}
Here, each call to fgetc()
reads one byte, and we increment a counter until the end of the file. This is easy to understand but slower for large files.
Program 5: Using lseek()
on File Descriptors
For lower-level file handling with system calls, you can use lseek()
to determine file size.
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
int main() {
const char *filename = "data.txt";
int fd = open(filename, O_RDONLY);
if (fd < 0) {
perror("Error opening file");
return 1;
}
off_t size = lseek(fd, 0, SEEK_END);
if (size == (off_t)-1) {
perror("Error determining file size");
close(fd);
return 1;
}
close(fd);
printf("Size of file '%s' is %lld bytes.\n", filename, (long long)size);
return 0;
}
Here, lseek(fd, 0, SEEK_END)
moves the file pointer to the end and returns its position, which corresponds to the file size. This method is efficient and works well for system-level operations.
FAQs
Q1: Can I find the size of a file without opening it?
Yes. Using stat()
or fstat()
allows you to retrieve file metadata, including size, without opening the file for reading. This is useful when you only need information about the file and don’t want to process its contents.
Q2: Does this method work for all types of files?
These methods work reliably for regular files. However, special files such as pipes, sockets, or devices may not report a meaningful size, or their size may change dynamically depending on system activity.
Q3: Why use binary mode with fseek()
and ftell()
?
Binary mode prevents newline translations that can occur in text mode, ensuring that the file pointer reflects the exact number of bytes in the file. Text mode may cause ftell()
to return an inaccurate byte count on some systems.
Q4: Which method is more efficient for large files?stat()
is usually more efficient because it does not require opening the file or moving the file pointer. Methods using fseek()
and ftell()
involve opening the file and seeking to the end, which can be slower for very large files.
Conclusion
Determining the size of a file in C can be achieved using several methods, each suited to different needs. Using fseek()
and ftell()
is simple and portable, ideal when you intend to read the file. The stat()
or fstat()
approach is more efficient when you only need the file size and other metadata without opening the file. Low-level functions like lseek()
provide precise control over file descriptors and are useful in system-level programming.
Understanding these techniques allows you to write programs that handle files safely, allocate memory correctly, and process data efficiently. Whether you are building utilities, reading large datasets, or managing system resources, knowing how to accurately determine file size is a fundamental skill that improves both the reliability and performance of your C programs.
References & Additional Resources
A curated collection of textbooks, tutorials, and documentation for learning file handling, file size calculation, and position tracking in C.
- Kernighan, B.W., & Ritchie, D.M. (1988). The C Programming Language (2nd Edition). Prentice Hall – Classic reference covering file handling,
fseek()
,ftell()
, and standard I/O operations in C. - C Library
fseek()
Documentation – Official reference for moving the file position indicator. - C Library
ftell()
Documentation – Official reference for retrieving the current position in a file. - GeeksforGeeks: File Size in C – Practical example for calculating the size of a file in C.
- Linux man page: stat – POSIX system call for retrieving file metadata, including size, permissions, and timestamps.
- TutorialsPoint: C File I/O – Beginner-friendly guide to file operations such as reading, writing, and determining file size.
- Stack Overflow: File Size Calculation in C – Community discussion with multiple approaches for determining file size efficiently.