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));
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));
May 2nd, 2010 - 07:21
much appreciated
May 2nd, 2010 - 12:57
You’re welcome
Thanks for leaving a comment!