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

1.读取CSV文件

cpp 复制代码
// 读取csv文件
void read_csv(const std::string& file_path) {
  std::cout<<"文件路径: "<< file_path<<"\n";
  std::ifstream csv_data(file_path, std::ios::in);
  std::string line;

  if (!csv_data.is_open()) {
    std::cout << "Error: failed to open file\n";
    std::exit(1);
  }

  std::istringstream sin;  // 将整行字符串读入到字符串流中
  std::vector<std::string> words;
  std::string word;
  std::vector<std::vector<double>> path_points;

  // 读取标题行
  std::getline(csv_data, line);
  // 读取数据
  while (std::getline(csv_data, line)) {
    sin.clear();
    sin.str(line);
    words.clear();
    std::vector<double> path_point;
    while (std::getline(
        sin, word, ',')) {  // 将字符串流sin中的字符读到word中,以字符'逗号'为分隔符
      double value = std::atof(word.c_str());
      path_point.push_back(value);
    }
    path_points.push_back(path_point);
  }

  csv_data.close();  // 关闭文件
}

2.写入CSV文件

cpp 复制代码
void write_csv(const std::string& file_path) {
  std::cout << "写入路径为: " << file_path << "\n";
  std::ofstream out_file(
      file_path,
      std::ios::out);  // 默认通过iso::out方式进行写入,当文件不存在时会进行创建
  if (out_file.is_open()) { //判定文件是否打开
    // 写入标题行
    out_file << "x" << ',' << "y" << ',' << "heading" << ',' << "s" << ','
             << "kappa" << ',' << "flag" << std::endl;

    // 写入10行数据
    for (int i = 0; i < 10; ++i) {
      out_file << std::to_string(i) << ',' << std::to_string(i) << ','
               << std::to_string(i) << ',' << std::to_string(i) << ','
               << std::to_string(i) << ',' << std::to_string(i) << std::endl;
    }

    out_file.close();
  }else{
    std::cout<<"文件无法打开\n";
  }

}

3.向csv文件中追加内容

与第2部分基本相同,只不过是以iso::app方式打开,当文件不存在时会自动创建。

cpp 复制代码
void app_csv(const std::string& file_path) {
  std::ofstream out_file(file_path, std::ios::app);
  if(out_file.is_open()){ //判断文件是否打开
    // 写入10行数据
    for (int i = 10; i < 20; ++i) {
      out_file << std::to_string(i) << ',' << std::to_string(i) << ','
               << std::to_string(i) << ',' << std::to_string(i) << ','
               << std::to_string(i) << ',' << std::to_string(i) << std::endl;
    }
  }else{
    std::cout<<"文件无法打开\n";
  }
}
相关推荐
jdksjw5 分钟前
同步与异步、阻塞与非阻塞、多线程、协程超详细讲解(Python并发编程从入门到精通)
开发语言·python
Zach_菠萝侠9 分钟前
【DeepSeek Harness 研究】进化方向4:安全加固 思考、设计与实现
开发语言·安全·deepseek
ShineWinsu31 分钟前
对于C++:布隆过滤器(bloomfilter)的详细解析
c++·面试·位图·位运算·布隆过滤器·海量数据·比特位
SL-staff1 小时前
技术实践:HR如何用JVS-Logic可视化编排实现考勤数据同步(含节点配置与异常处理)
开发语言·python·低代码·钉钉·可视化编排·jvs-logic·hr技术
SomeB1oody1 小时前
【RustyML入门】6.0. 数学工具
开发语言·后端·机器学习·rust·教程
进制树2 小时前
【飞控开发实战·⑲】ROS2无人机开发环境搭建:Jazzy安装、工作空间与hello_drone节点实战
开发语言·安全·无人机·课程设计
牛马也想出海2 小时前
亚马逊爬虫代理IP:IP类型选择与配置指南
开发语言·php
菜冻鱼3 小时前
Python-pytorch-高级技巧
开发语言·人工智能·pytorch·python·深度学习·神经网络·聚类
lpfasd1233 小时前
python webview打包版卡死、开发版正常
开发语言·python
weixin_461408583 小时前
npm npx yarn
开发语言·前端·javascript