C++对txt文件进行读,写,追加操作

1.读取txt文件

// 读取txt文件(文件中的数据以空格为间隔)
bool read_txt(const std::string& file_path) {
  std::ifstream infile;
  infile.open(file_path);  // 将文件流对象与文件关联起来,默认以只读方式打开std::ios::in
  if (!infile.is_open()) {
    return false;
  }
  std::vector<std::vector<double>> path_points;
  std::string line, x, y, s, heading, kappa;
  while (getline(infile, line)) {  // 读取一行
    std::stringstream words(
        line);  // 创建字符串流对象,然后将每个words写入到字符串变量中
    words >> x;
    words >> y;
    words >> s;
    words >> heading;
    words >> kappa;

    double pt_x = std::atof(x.c_str());  // 将字符串转换为float
    double pt_y = std::atof(y.c_str());
    double pt_s = std::atof(s.c_str());
    double pt_heading = std::atof(heading.c_str());
    double pt_kappa = std::atof(kappa.c_str());

    path_points.push_back({pt_x, pt_y, pt_s, pt_heading, pt_kappa});
  }

  infile.close();
}

2.写入内容

以std::ios::out方式打开,如果文件不存在,则会创建

void write_txt(const std::string& file_path) {
  std::ofstream out_file;
  out_file.open(file_path, std::ios::out);
  if(out_file.is_open()){
    //输入标题行
    out_file<<"x"<<' '<<"y"<<' '<<"z"<<std::endl;

    out_file.close(); //关闭文件
  }else{
    std::cout<<"文件打开失败\n";
  }

}

3.追加内容

以std::ios::app方式打开,进行追加,若文件不存在则会创建

void app_txt(const std::string& file_path) {
  std::ofstream out_file;
  out_file.open(file_path, std::ios::app);
  if (out_file.is_open()) {
    //
    out_file << std::to_string(0) << ' ' << std::to_string(1) << ' '
             << std::to_string(2) << ' ' << std::to_string(1) << ' '
             << std::to_string(1) <<std::endl;

    out_file.close();  // 关闭文件
  } else {
    std::cout << "文件打开失败\n";
  }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值