能否用一行C++代码实现类似Python path.read_bytes()的字节读取?
C++读取
/proc/device-tree/soc_id的简洁方案 C++17的实现
C++17标准库没有提供直接一行读取二进制小文件的函数,但可以通过封装函数实现调用时的一行写法,或者用lambda表达式直接写出一行代码:
封装函数后调用(推荐,可读性好)
#include <fstream> #include <array> #include <cstdint> uint32_t read_soc_id() { std::array<char, 4> buf{}; std::ifstream("/proc/device-tree/soc_id", std::ios::binary).read(buf.data(), buf.size()); return *reinterpret_cast<const uint32_t*>(buf.data()); } // 调用时就是一行代码 auto soc_id = read_soc_id();
直接一行lambda写法
#include <fstream> #include <array> #include <cstdint> auto soc_id = []{ std::array<char,4> buf{}; std::ifstream("/proc/device-tree/soc_id", std::ios::binary).read(buf.data(),4); return *reinterpret_cast<const uint32_t*>(buf.data()); }();
C++23的优化
C23可以借助C20引入的std::bit_cast(类型安全的转换),结合封装函数实现更规范的一行调用:
#include <fstream> #include <array> #include <cstdint> #include <bit> uint32_t read_soc_id() { std::array<std::byte, 4> buf{}; std::ifstream("/proc/device-tree/soc_id", std::ios::binary).read(reinterpret_cast<char*>(buf.data()), buf.size()); return std::bit_cast<uint32_t>(buf); } // 调用一行完成 auto soc_id = read_soc_id();
C++23本身也没有新增专门的一行读文件标准函数,但借助已有特性可以让代码更安全规范。
C++26的展望
目前C++26的提案中包含文件IO简化的相关内容,预计可能会引入类似std::filesystem::read_binary这类直接读取文件二进制内容的函数,届时可能真的能做到一行代码完成读取:
#include <filesystem> #include <cstdint> #include <bit> auto soc_id = std::bit_cast<uint32_t>(std::filesystem::read_binary("/proc/device-tree/soc_id"));
不过最终是否落地还要看标准的最终确定。
内容的提问来源于stack exchange,提问作者Keelung
相关产品推荐
相关产品推荐

