C++ 读写结构体文件

读文件

#include 
#include 
#include 

// 定义结构体类型
typedef struct NIoSocket_temperature
{
    float front_right_cheek_temper;    // 主驾驶脸颊温度:
    float front_right_forehead_temper; // 主驾驶额头温度:
    float front_right_thermal_comfort; // 主驾驶热感受

    float front_left_cheek_temper;
    float front_left_forehead_temper;
    float front_left_thermal_comfort;

    float back_cheek_temper;
    float back_forehead_temper;
    float back_thermal_comfort;

    float roof_temper;

} Nio_tempera;

int main() {
    // 以二进制模式打开文件
    std::ifstream infile("data.bin", std::ios::binary | std::ios::in);
    if (!infile.is_open()) {
        std::cerr << "Failed to open the file." << std::endl;
        return 1;
    }

    // 使用循环逐个读取结构体,直到到达文件末尾
    std::vector<Nio_tempera> dataList;
    while (!infile.eof()) {
        Nio_tempera data;
        infile.read(reinterpret_cast<char*>(&data), sizeof(Nio_tempera));
        // 检查是否成功读取了一个完整的结构体
        if (infile.gcount() == sizeof(Nio_tempera)) {
            dataList.push_back(data);
        }
    }

    // 关闭文件
    infile.close();

    // 输出读取到的结构体数据
    for (const auto& data : dataList) {
        std::cout << "Data { a: " << data.front_right_cheek_temper << ", b: " << data.front_right_forehead_temper << ", c: " << data.front_right_thermal_comfort << " }" << std::endl;
    }

    return 0;
}

写文件

std::ofstream outfile("data.bin", std::ios::binary | std::ios::out);

if (!outfile.is_open()) {
    std::cerr << "Failed to open the file." << std::endl;
    // return 1;
}
outfile.write(reinterpret_cast<const char*>(&Nio_tempera_tmp), sizeof(Nio_tempera_tmp));

你可能感兴趣的:(c++,开发语言)