在 C++ 中,可以使用以下代码来读取文件内容为 16 进制数字:

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>

std::vector<unsigned char> readFile(const std::string& filePath) {
    std::ifstream file(filePath, std::ios::binary);
    if (!file) {
        throw std::runtime_error("Failed to open file: ' + filePath);
    }

    std::stringstream buffer;
    buffer << file.rdbuf();

    std::string hexString = buffer.str();
    std::vector<unsigned char> data;

    for (size_t i = 0; i < hexString.size(); i += 2) {
        std::string byteString = hexString.substr(i, 2);
        unsigned char byte = static_cast<unsigned char>(std::stoi(byteString, nullptr, 16));
        data.push_back(byte);
    }

    return data;
}

int main() {
    std::string filePath = "D:/workspace_zq/VDR材料/D230316_1131_xH85E93.VDR";
    try {
        std::vector<unsigned char> data = readFile(filePath);

        // Process the data blocks
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    return 0;
}

上述代码中,readFile 函数接受文件路径作为参数,并返回一个包含 16 进制数字的 std::vector<unsigned char>。在 main 函数中,你可以进一步处理文件内容的数据块。

C++ 读取文件并解析为 16 进制数据

原文地址: https://www.cveoy.top/t/topic/fK6z 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录