Human-readable file size in C

I did a quick search on Google and couldn’t find any code that did this in C/C++, so here’s my contribution for the day. Just remember the allocate enough space in the buffer — about 10 chars should be enough.

char* readable_fs(double size/*in bytes*/, char *buf) {
    int i = 0;
    const char* units[] = {"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
    while (size > 1024) {
        size /= 1024;
        i++;
    }
    sprintf(buf, "%.*f %s", i, size, units[i]);
    return buf;
}

// usage
struct stat info;
char buf[10];
lstat("somefile.txt", &info);
printf("File size: %s\n", readable_fs(info.st_size, buf));
Posted in

8 thoughts on “Human-readable file size in C

  1. You’re welcome 🙂 Thanks for leaving a comment!

  2. Nice code, thanks =)

    Changed

    while (size > 1024) {

    to

    while (size >= 1024) {

    so that instead of returning ‘1024MB’ it returns ‘1.000GB’ etc…

  3. I think you’d would want to check for overflow with i:

    `while (size >= 1024 && i+1 < 9)`

Leave a Reply

Your email address will not be published. Required fields are marked *