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";
  }
}
相关推荐
漫路在线19 分钟前
JS逆向-某易云音乐下载器
开发语言·javascript·爬虫·python
小辉懂编程1 小时前
C语言:51单片机实现数码管依次循环显示【1~F】课堂练习
c语言·开发语言·51单片机
醍醐三叶2 小时前
C++类与对象--2 对象的初始化和清理
开发语言·c++
Magnum Lehar3 小时前
3d游戏引擎EngineTest的系统实现3
java·开发语言·游戏引擎
Mcworld8573 小时前
java集合
java·开发语言·windows
成功人chen某3 小时前
配置VScodePython环境Python was not found;
开发语言·python
wuqingshun3141593 小时前
蓝桥杯 16. 外卖店优先级
c++·算法·职场和发展·蓝桥杯·深度优先
海绵宝宝贾克斯儿4 小时前
C++中如何实现一个单例模式?
开发语言·c++·单例模式
史迪仔01124 小时前
[python] Python单例模式:__new__与线程安全解析
开发语言·python·单例模式
Epiphany.5564 小时前
素数筛(欧拉筛算法)
c++·算法·图论