Program & Design Tips, tricks, tutorials, and tools on programming & web design

18Mar/092

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));
Filed under: C++ Leave a comment
Comments (2) Trackbacks (0)
  1. much appreciated

  2. You’re welcome :) Thanks for leaving a comment!


Leave a comment


No trackbacks yet.