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";
  }
}
相关推荐
CodeWithMe19 分钟前
【C/C++】EBO空基类优化介绍
开发语言·c++
404.Not Found29 分钟前
Day46 Python打卡训练营
开发语言·python
love530love31 分钟前
【PyCharm必会基础】正确移除解释器及虚拟环境(以 Poetry 为例 )
开发语言·ide·windows·笔记·python·pycharm
凌辰揽月32 分钟前
Web后端基础(基础知识)
java·开发语言·前端·数据库·学习·算法
海奥华236 分钟前
go中的接口返回设计思想
开发语言·后端·golang
lifallen38 分钟前
深入浅出 Arrays.sort(DualPivotQuicksort):如何结合快排、归并、堆排序和插入排序
java·开发语言·数据结构·算法·排序算法
运维开发王义杰38 分钟前
Python: 告别 ModuleNotFoundError, 解决 pipx 环境下 sshuttle 缺少 pydivert 依赖的终极指南
开发语言·python
k要开心40 分钟前
从C到C++语法过度1
开发语言·c++
小吕学编程43 分钟前
策略模式实战:Spring中动态选择商品处理策略的实现
java·开发语言·设计模式
whoarethenext1 小时前
使用 C/C++的OpenCV 实时播放火柴人爱心舞蹈动画
c语言·c++·opencv