C/C++: Get the size of a file in bytes
The following function accepts the name of a file as a string and returns the size of the file in bytes. If for any reason it cannot get the file information, it will return the value -1.
[download id=”2417″]
In our header file, we used the following pre-processor directives around our declarations
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus } #endif
to allow c++ code to call our c function.
The usage example code makes three tests:
- Getting the size of the currently executing binary, as it will have a non-zero size
- Getting the size of a non-existing file, to check that it will properly return
-1 - Getting the size of an empty file, to be sure it is empty we create it right before the test
[download id=”2417″]
Source file (file_helpers.c)
#include <sys/stat.h>
#include "file_helpers.h"
//It will return the size of the file in bytes OR -1 in case that it cannot get any status information for it
off_t get_file_size(const char *filename) {
//Specialised struct that can hold status attributes of files.
struct stat st;
//Gets file attributes for filename and puts them in the stat buffer.
// Upon successful completion, it returns 0, otherwise and errno will be set to indicate the error.
if (stat(filename, &st) == 0) {
//Size of file, in bytes.
return st.st_size;
}
return -1;
}
Header file (file_helpers.h)
#ifndef GM_S_LITTLE_HELPERS_FILE_HELPERS_H
#define GM_S_LITTLE_HELPERS_FILE_HELPERS_H
#ifdef __cplusplus
extern "C" {
#endif
off_t get_file_size(const char *filename);
#ifdef __cplusplus
}
#endif
#endif //GM_S_LITTLE_HELPERS_FILE_HELPERS_H
Usage example (main.cpp)
#include <iostream>
#include "file_helpers.h"
void print_file_size(const char *filename) {
const off_t size_of_file = get_file_size(filename);
if (size_of_file > 0) {
printf("The size of '%s' is %zd bytes\n", filename, size_of_file);
}
else if (size_of_file == 0) {
printf("The file '%s' is empty\n", filename);
}
else {
printf("Could not get the status information for file '%s'\n", filename);
}
}
int main(int argc, char *argv[]) {
//Testing a non-zero sized file
print_file_size(argv[0]);
//Testing for a non-existing file
print_file_size("some file that does not exist...");
const char * filename = "/tmp/some_empty_file";
//Creating an empty file
FILE * fout = fopen(filename, "w");
fclose(fout);
//Testing for an empty file
print_file_size(filename);
return 0;
}
[download id=”2417″]





