C++数据格式化2 - 将文件大小转换为人类易读的格式
1. 关键词
C++ 数据格式化 字符串处理 std::string 文件大小 跨平台
2. strfmt.h
#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
#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. 测试代码
#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. 运行结果
-----------------------------------------TestFormatFileSize-----------------------------------------
fmt_filesize 1: 361.2M
fmt_filesize 2: 361.17M
fmt_filesize 2: 361.17MB
6. 源码地址
更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号