在C中将字节数转换为文件大小
我想将单个字节数转换为文件大小(具有 .KB、.MB 和 .GB)。
如果数字是 0,我不想有任何单位。 如果该数字可以被 1024 的倍数整除(不是浮点数),那么我将打印: x 。否则,我想以一度精度打印浮点数。
我写了一些代码,看起来效果很好,但是很麻烦。我正在研究如何使我的功能更清洁/更高效,老实说,它非常丑陋:
char *
calculateSize( off_t size )
{
char *result = (char *) malloc(sizeof(char) * 20);
static int GB = 1024 * 1024 * 1024;
static int MB = 1024 * 1024;
static int KB = 1024;
if (size >= GB) {
if (size % GB == 0)
sprintf(result, "%d GB", size / GB);
else
sprintf(result, "%.1f GB", (float) size / GB);
}
else if (size >= MB) {
if (size % MB == 0)
sprintf(result, "%d MB", size / MB);
else
sprintf(result, "%.1f MB", (float) size / MB);
}
else {
if (size == 0) {
result[0] = '0';
result[1] = '\0';
}
else {
if (size % KB == 0)
sprintf(result, "%d KB", size / KB);
else
sprintf(result, "%.1f KB", (float) size / KB);
}
}
return result;
}
如果有人有更好的方法来实现相同的结果,我将非常感激。
I want to convert a single number of bytes, into a file size (that has .KB, .MB and .GB).
If the number is 0, I don't want to have any unit.
If the number is exactly divisible by a multiple of 1024 (not a floating point), then I will print: x . Otherwise, I want to print a floating point with one degree precision.
I made some code that seems to work well, but it's very cumbersome. I'm looking into ways I could make my function cleaner/more efficient please, it's honestly VERY ugly:
char *
calculateSize( off_t size )
{
char *result = (char *) malloc(sizeof(char) * 20);
static int GB = 1024 * 1024 * 1024;
static int MB = 1024 * 1024;
static int KB = 1024;
if (size >= GB) {
if (size % GB == 0)
sprintf(result, "%d GB", size / GB);
else
sprintf(result, "%.1f GB", (float) size / GB);
}
else if (size >= MB) {
if (size % MB == 0)
sprintf(result, "%d MB", size / MB);
else
sprintf(result, "%.1f MB", (float) size / MB);
}
else {
if (size == 0) {
result[0] = '0';
result[1] = '\0';
}
else {
if (size % KB == 0)
sprintf(result, "%d KB", size / KB);
else
sprintf(result, "%.1f KB", (float) size / KB);
}
}
return result;
}
I would really appreciate if someone has a better way to achieve the same result please.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用扩展到 EiB 的表驱动表示。
测试代码
测试输出
Using a table-driven representation extended up to EiB.
Test code
Test output
我会使用表格方法。大致如下:
I'd use a table approach. Something along the lines of:
更好的方法是:
必须释放函数的结果。
A nicer way would be:
The result of the function must be freed.