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));
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));
8 thoughts on “Human-readable file size in C”
much appreciated
spanky
You’re welcome 🙂 Thanks for leaving a comment!
Mark
Thnaks buddy, saved my day! 🙂
sameera
Nice and short.A lot thanks
john
Thank you!
Jackson Sousa
Nice code, thanks =)
Changed
to
so that instead of returning ‘1024MB’ it returns ‘1.000GB’ etc…
Chris Firth
Thanks a lot <3
ѦՊԻ
I think you’d would want to check for overflow with i:
`while (size >= 1024 && i+1 < 9)`
koosha