将 bytes 转为可读的单位
Moevis
代码来自:http://programanddesign.com/cpp/human-readable-file-size-in-c/
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));
不过很奇怪这一句:
sprintf(buf, "%.*f %s", i, size, units[i]);
其实去掉 size 也可以运行的,很奇怪反正。