C++读、写文件:bin、txt

读写bin二进制文件:

读取bin二进制文件:

std::ifstream R_pose_file("../data/pose.bin", std::ios::in | std::ios::binary);
while (!R_pose_file.eof())
{
    Pose_R R_temp;
    R_pose_file.read(reinterpret_cast<char *>(&R_temp), sizeof(Pose_R));
}
R_pose_file.close();


struct Pose_R
{
    Eigen::Matrix4d pose;
    double time;
};

写入bin二进制文件:

string save_bin_path = "../pose.bin";
std::ofstream pose_bin(save_bin_path);

pose_bin.write(reinterpret_cast<const char *>(&pose_save), sizeof(Pose_R));

pose_bin.close();

 读取txt文件然后储存到bin文件:

void SavePoseTxtToBin(const std::string pose_txt_path, const std::string save_bin_path)
{
    std::ifstream pose_txt(pose_txt_path);
    std::ofstream pose_bin(save_bin_path);

    std::string line, data_in;
    int index = 0;
    while (getline(pose_txt, line))
    {
        Pose pose_save;
        pose_save.index = index++;

        std::istringstream iss(line);
        iss >> pose_save.time >> pose_save.pose_x >> pose_save.pose_y >> pose_save.pose_theta;
        pose_bin.write(reinterpret_cast<const char *>(&pose_save), sizeof(CartographerPose));

        iss.clear();
        iss.str("");
    }

    pose_txt.close();
    pose_bin.close();
}

struct Pose {
    int index;
    double pose_x;
    double pose_y;
    double pose_theta;
    unsigned long long time;
};

读写txt文件:

std::ifstream ground_truth_file("../groundtruth.txt");
std::ofstream pose_voice_file("../pose_voice.txt");

cv::RNG rng;  
std::string line, data_in;

while (getline(ground_truth_file, line))
{
    // 读取txt文件
    std::istringstream input_string_stream(line);
    double timestemp, px, py, pz, qx, qy, qz, qw, a_voice, b_voice;
    input_string_stream >> timestemp >> px >> py >> pz >> qx >> qy >> qz >> qw;
    // 将读取到的数据添加高斯噪声
    a_voice = px + rng.gaussian(0.08);
    b_voice = py + rng.gaussian(0.08);
    // 写入txt文件,并指定精度
    pose_voice_file.precision(16);
    pose_voice_file << timestemp << " " << a_voice << " " << b_voice << std::endl;

    input_string_stream.clear();
    input_string_stream.str("");
}

ground_truth_file.close();
pose2d_voice_file.close();

需要添加头文件:

#include <iostream>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值