You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

uintmax_t转int出错:获取W盘总容量数值异常的问题

问题分析与修复

你的问题确实是类型转换溢出导致的:

  • std::filesystem::space_info::capacity的实际类型是uintmax_t(无符号64位整数),而你强行将其转换为32位的int——int的最大值通常仅为2147483647,远小于你磁盘的实际容量1022828212224,转换时发生溢出,得到错误的小数值。

修复后的代码

#include <iostream>
#include <filesystem>

int main() {
    // 保留原类型uintmax_t,避免数值截断
    uintmax_t size = std::filesystem::space("\\\\.\\W:").capacity;
    // std::cout原生支持uintmax_t类型的输出
    std::cout << "\nCAPACITY: " << size << '\n';
}

额外说明

  • 如果需要将数值转为字符串处理,C++20及以上标准支持直接对uintmax_t使用std::to_string;若使用旧标准,可先转换为unsigned long long再操作:
    std::cout << "\nCAPACITY: " << std::to_string(static_cast<unsigned long long>(size)) << '\n';
    
  • 存储大磁盘容量时,必须使用64位整数类型(uintmax_t、unsigned long long、int64_t等),禁止使用int、long这类32位类型,避免再次出现溢出问题。

内容的提问来源于stack exchange,提问作者milkchunks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.02 04:33:10