Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

1. 关键词

C++ 数据格式化 字符串处理 std::string 文件大小 跨平台

2. strfmt.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#pragma once

#include <string>
#include <cstdint>
#include <sstream>
#include <iomanip>

namespace cutl
{
/**
* @brief Format a file size to a human-readable string with a given precision.
*
* @param size the size to be formatted.
* @param simplify whether to use a simplify unit.
* @param precision the precision of the formatted string, default is 1.
* @return std::string the formatted string.
*/
std::string fmt_filesize(uint64_t size, bool simplify = true, int precision = 1);
} // namespace cutl

3. strfmt.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <sstream>
#include <iomanip>
#include <bitset>
#include "strfmt.h"

namespace cutl
{
std::string fmt_filesize(uint64_t size, bool simplify, int precision)
{
static const double KBSize = 1024;
static const double MBSize = 1024 * 1024;
static const double GBSize = 1024 * 1024 * 1024;
const std::string gb = simplify ? "G" : "GB";
const std::string mb = simplify ? "M" : "MB";
const std::string kb = simplify ? "K" : "KB";
const std::string byte = simplify ? "B" : "Byte";

if (size > GBSize)
{
double hSize = (double)size / GBSize;
return fmt_double(hSize, precision) + gb;
}
else if (size > MBSize)
{
double hSize = (double)size / MBSize;
return fmt_double(hSize, precision) + mb;
}
else if (size > KBSize)
{
double hSize = (double)size / KBSize;
return fmt_double(hSize, precision) + kb;
}
else
{
return fmt_double(size, precision) + byte;
}

return "";
}
} // namespace cutl

4. 测试代码

1
2
3
4
5
6
7
8
9
10
11
#include "common.hpp"
#include "strfmt.h"

void TestFormatFileSize()
{
PrintSubTitle("TestFormatFileSize");

std::cout << "fmt_filesize 1: " << cutl::fmt_filesize(378711367) << std::endl;
std::cout << "fmt_filesize 2: " << cutl::fmt_filesize(378711367, true, 2) << std::endl;
std::cout << "fmt_filesize 2: " << cutl::fmt_filesize(378711367, false, 2) << std::endl;
}

5. 运行结果

1
2
3
4
-----------------------------------------TestFormatFileSize-----------------------------------------
fmt_filesize 1: 361.2M
fmt_filesize 2: 361.17M
fmt_filesize 2: 361.17MB

6. 源码地址

更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。

推荐阅读
C++数据格式化1 - uint转换成字符串 & double转换成字符串 C++数据格式化1 - uint转换成字符串 & double转换成字符串 C++数据格式化3 - 格式化时间区间(使用时长) C++数据格式化3 - 格式化时间区间(使用时长) C++数据格式化4 - 格式化时间戳 C++数据格式化4 - 格式化时间戳

评论