C++ 中的 CSV 处理:库与实践示例
CSV(逗号分隔值)是存储表格数据最常用的格式之一。在 C++ 标准库中(直到 C++23)没有内置的 CSV 支持,因此开发者会使用第三方库或编写自己的解析器。本文将介绍 C++ 中处理 CSV 的主要方法:从手动解析到现成的解决方案。
为什么需要 CSV 库?
CSV 文件看似简单,但实际上包含许多陷阱:
- 字段内的引号转义(例如
"Hello, world") - 多行值
- 不同的分隔符(逗号、分号、制表符)
- 不同的编码(UTF-8、UTF-16、ANSI)
现成的库可以解决这些问题并节省时间。
1. 手动解析 CSV(不使用第三方库)
对于简单情况,可以自行编写解析器。使用 std::ifstream 和 std::getline 读取 CSV 的示例:
#include <iostream>#include <fstream>#include <sstream>#include <vector>#include <string>
std::vector<std::vector<std::string>> parseCSV(const std::string& filename) { std::vector<std::vector<std::string>> data; std::ifstream file(filename); std::string line;
while (std::getline(file, line)) { std::vector<std::string> row; std::stringstream ss(line); std::string cell;
while (std::getline(ss, cell, ',')) { // 移除多余的引号(简化处理) if (cell.size() >= 2 && cell.front() == '"' && cell.back() == '"') { cell = cell.substr(1, cell.size() - 2); } row.push_back(cell); } data.push_back(row); } return data;}缺点: 不处理引号内的转义逗号、多行字段以及文件末尾的空行。
2. libcsv 库(C 语言)
libcsv 是一个轻量级的 C 语言库,能够根据 RFC 4180 正确解析 CSV。适用于对性能要求较高的项目。
安装(Linux):sudo apt-get install libcsv-dev
#include <csv.h>#include <iostream>#include <vector>
void cb1(void *s, size_t len, void *data) { std::string field(static_cast<char*>(s), len); static_cast<std::vector<std::string>*>(data)->push_back(field);}
void cb2(int c, void *data) { if (c == CsvRowEnd) { // 行结束——输出 auto& row = *static_cast<std::vector<std::string>*>(data); for (const auto& f : row) std::cout << f << " | "; std::cout << ""; row.clear(); }}
int main() { FILE *fp = fopen("data.csv", "r"); if (!fp) return 1;
struct csv_parser p; csv_init(&p, CSV_STRICT);
std::vector<std::string> row; char buf[1024]; size_t bytes_read;
while ((bytes_read = fread(buf, 1, sizeof(buf), fp)) > 0) { csv_parse(&p, buf, bytes_read, cb1, cb2, &row); } csv_fini(&p, cb1, cb2, &row); csv_free(&p); fclose(fp); return 0;}3. rapidcsv 库(C++ 仅头文件)
rapidcsv 是一个现代的 C++17 库,仅需头文件即可使用。支持自动检测分隔符、处理不同数据类型以及写入 CSV。
安装:将 rapidcsv.h 复制到项目中。
#include "rapidcsv.h"#include <iostream>#include <vector>
int main() { // 读取 CSV rapidcsv::Docum