Thursday, August 28, 2014

C++ - Get File Size in KB/MB/GB Format using stat()

This code uses stat() function of the built-in sys/stat.h header file, to get the size of a file.

The size is then passed to convertSize function which converts the file size to a suitable unit and returns the result as a string value.

You might want to know that stat(), however, isn't part of the C++ standard, so it may or may not be available in your compiler.

These utility functions are really useful and might come in handy for you in solving other problems as well.

#include <iostream>
#include <string>
#include <sstream>
#include <windows.h>
#include <sys/stat.h> /* for stat() function */

using namespace std;

// Utility functions:


string convertToString(double num) {
    ostringstream convert;
    convert << num;
    return convert.str();
}

double roundOff(double n) {
    double d = n * 100.0;
    int i = d + 0.5;
    d = (float)i / 100.0;
    return d;
}

string convertSize(size_t size) {              
    static const char *SIZES[] = { "B", "KB", "MB", "GB" };
    int div = 0;
    size_t rem = 0;

    while (size >= 1024 && div < (sizeof SIZES / sizeof *SIZES)) {
        rem = (size % 1024);
        div++;
        size /= 1024;
    }

    double size_d = (float)size + (float)rem / 1024.0;
    string result = convertToString(roundOff(size_d)) + " " + SIZES[div];
    return result;
}

int file_size(const char *path) {
    struct stat results;

    if (stat(path, &results) == 0) {
        return results.st_size;
    } else {
        return -1;
    }
}

// This is the function that you will call:
string getFileSize(string path) {
    size_t size = file_size((const char *)path.c_str());
    return convertSize(size);
}


// Example program:
int main() {
    cout << getFileSize("D:\\httrack_x64-3.48.13.exe") << endl;
    return 0;
}


This code has been test with Visual Studio 2008 and Dev-C++. If you have any problems running this code, please comment below. I will be glad to help you out.

Tags: C++, convert size, file size in c++, round off, size in string, length of file in c++

0 comments:

Post a Comment