Friday, April 29, 2011

How to find the size of a file in C++?

We need to use the combination of fseek and ftell functions. Here's one such implementation. This implementation will return a '-1' in case it'll not be able to open the file, else returns the size of the file (in B).

#include <stdio.h>
/**
 * @brief Finds the size of the file (in B)
 * @param file name of the file
 * @return if file-open fails, returns a value of -1; else size of the file.
 */
int sizeOfFile(const char *file) {
    FILE* fp = fopen(file, "rb");
    if(fp == NULL) { return -1; }
    fseek(fp, 0, SEEK_END);
    int i = ftell(fp);
    fclose(fp);
    return i;
}

I tried to verify the performance of the above function, using the piece of code below:
int main(int argc, char** argv) {
    if(argc != 2) {
        fprintf(stderr, "USAGE: %s <fileToBeRead>\n", argv[0]);
        return 1;
    }
    for(int i=0;i<10000;i++) {
        sizeOfFile(argv[1]);
    }
    return 0;
}

I copied above 2 pieces of code into a file named 'test_perf.cpp'. Then, I compiled using the command: 'g++ -o perf test_perf.cpp' in cygwin version 1.7. Here's my result: [System: Dell Latitude E6400, Win7, 32b]
$ time ./perf.exe perf.exe
real    0m2.677s
user    0m0.342s
sys     0m1.887s
$ stat perf.exe
  File: `perf.exe'
  Size: 19596           Blocks: 20         IO Block: 65536  regular file
 .... some more outputs hidden for privacy reasons ....

No comments:

Post a Comment