Vince's CSV Parser
- Vince's CSV Parser
- Motivation
- Documentation
- Sponsors
- Integration
- Features & Examples
- Reading an Arbitrarily Large File (with Iterators)
- Memory-Mapped I/O and Streams
- Indexing by Column Names
- Numeric, Boolean, and Timestamp Conversions
- Converting to JSON
- Specifying the CSV Format
- Parsing an In-Memory String
- DataFrames for Random Access and Editing
- High Performance Extract-Transform-Load with the DataFrame
- Writing CSV Files
Motivation
I wanted a CSV library that was fast and reliable without forcing you into either:
- A 1990s C-style API
- A high-level wrapper that murders
malloc()and your cache
This library tries to be fast for developers and fast for your computer.
Performance and Memory Requirements
This library combines SIMD-accelerated parsing, memory-mapped I/O, careful memory layout, minimal allocation, and parallel parsing to process large CSV files quickly, even when they exceed available RAM.
Specifically, this library implements a speculative parallel parsing algorithm based on the approach described by Ge, Li, Eilebrecht, Chandramouli, and Kossmann in "Speculative Distributed CSV Data Parsing for Big Data Analytics," SIGMOD '19, pp. 883-899, doi:10.1145/3299869.3319898.
Show me the numbers
On my computer (12th Gen Intel(R) Core(TM) i5-12400 @ 2.50 GHz), this parser can read
- a 1.4 GB Craigslist Used Vehicles Dataset in 0.48 seconds
- a 2.9 GB Car Accidents Dataset in 2.2 seconds
- an 11.3 GB tab-delimited metadata file in 12.36 seconds
All benchmarks shown are warm cache runs to focus on parser/CPU performance rather than disk I/O variability.
Compared to other libraries
For broader comparison data, including ETL and round-trip workloads against
fast-cpp-csv-parser and rapidcsv, see the
benchmark results. On modern desktop and laptop CPUs,
this is likely one of the fastest general-purpose C++ CSV ETL libraries for
realistic workloads. For "read once and discard" workflows, the speculative parallel
memory-mapped IO path overtakes fast-cpp-csv-parser with 2-4 threads, and
the DataFrame benchmarks beat rapidcsv on edit and save workflows.
Chunk Size and Thread Count Tuning
By default, the parser reads CSV data in 10MB chunks. 10MB was chosen after empirical testing to optimize throughput while minimizing memory and thread synchronization costs, but feel free to experiment with different numbers yourself.
A custom CSVFormat with chunk_size() can be passed to:
- Shrink the chunk size (down to a minimum of 500KB)
- Expand the chunk size (necessary if you encounter very large rows)
CSVFormat fmt;
fmt.chunk_size(100 * 1024 * 1024); // 100MB chunks
CSVReader reader("massive_rows.csv", fmt);
When speculative parsing is enabled, the parser may read a window of
chunk_size * worker_count bytes at a time.
Speculative parallel parsing starts at 50MB by default when runtime threading is enabled. You can adjust both the source-size threshold and worker count:
CSVFormat fmt;
fmt.speculative_parallel_min_bytes(50 * 1024 * 1024)
.speculative_parallel_threads(4);
CSVReader reader("large.csv", fmt);
For workload-specific tuning, build and run csv_tuning; see the
CSV Tuning Doxygen page.
Fully RFC 4180-Compliant (and Beyond) Parser
This CSV parser is a fully RFC 4180-compliant parser out of the box. We do not disable embedded newline detection by default just so we can look better on benchmarks.
Furthermore, this parser can:
- Infer dialect (column names and delimiter)
- Ignore comments in leading rows and elsewhere
- Handle rows of different lengths
- Handle Windows
\r\n, Unix\n, and old Mac\rnewlines seamlessly
By default, rows of variable length are silently ignored, although you may elect to keep them or throw an error.
Encoding
This CSV parser assumes ANSI/UTF-8 encoding and automatically strips UTF-8 byte-order marks (BOM).
Bug Reports
This CSV parser has:
- An extensive Catch2 test suite
- Tests of various CMake and non-CMake builds across g++, clang, MSVC, and MinGW
- Address, thread safety, and undefined behavior checks with ASan, TSan, and Valgrind (see GitHub Actions)
With that being said, I welcome genuine bug reports brought in good faith. This includes:
- Crashes, memory leaks, data corruption, or race conditions
- Incorrect parsing of valid CSV files
- Performance regressions on real-world data
- API issues that affect practical use cases
When reporting compiler or integration issues, please mention which form of the library you're using:
- Single-header
- Regular headers + your own build system
- CMake
Note: Please keep reports focused on real-world problems.
Questions about extremely edge-case behavior (e.g. "what should ,,, return?") do not belong in the issue tracker.
Documentation
In addition to the Features & Examples below, an extensive documentation site contains more examples, details, interesting features, and instructions for less common use cases.
Sponsors
If you use this library for work, please become a sponsor. Your donation will fund continued maintenance and development of the project.
Shameless plug: If you like this library, check out my side project Experiencer — a WYSIWYG resume editor with clean ATS-friendly HTML/CSS output and powerful AI intergration with MCP or REST.
Integration
While C++20 is recommended, C++11 is the minimum version required. This library makes extensive use of string views, and uses
Martin Moene's string view library if std::string_view is not available.
SIMD acceleration is enabled by default when the build/compiler flags support it. If needed, you can force scalar-only parsing with CSV_NO_SIMD=ON in CMake or by defining CSV_NO_SIMD 1 before including the library headers.
Exception support is detected automatically. Use -DCSV_ENABLE_EXCEPTIONS=OFF
with CMake, or your compiler's exception-disabled flags, to select the explicit-error
API. See the Godot / no-exceptions guide
for engine-owned resources, conversions, DataFrames, writing, and error semantics.
Threading Modes
By default, csv-parser uses threads. If CMake cannot find a thread library, threading is disabled
automatically. Threading has two layers:
- Reader threading: a background producer thread keeps
CSVReaderfed while your code consumes rows. - Speculative parallel parsing: automatic multi-worker parsing for large, filename-backed inputs when runtime threading is enabled.
For programs that parse many small CSVs, you can keep thread support compiled in but disable parser threading for a specific reader:
CSVFormat format;
format.threading(false);
CSVReader reader("small.csv", format); // parses synchronously on the caller thread
This runtime switch also disables speculative parallel parsing for that reader.
For large files, speculative parallel parsing is automatic. You can tune the worker count and size threshold:
CSVFormat format;
format.speculative_parallel_threads(0); // 0 = auto
format.speculative_parallel_min_bytes(50 * 1024 * 1024);
CSVReader reader("large.csv", format);
Use format.threading(false) if you want to force synchronous parsing and turn
off speculative parsing for a reader.
CSVReader::parse_worker_count() reports the active parser worker count, and
CSVReader::speculative_diagnostics() reports chunk/repair counters. Stream
readers still benefit from reader threading, but speculative parsing is primarily
intended for large file-backed inputs.
You can also disable it explicitly:
CMake
set(CSV_ENABLE_THREADS OFF)
add_subdirectory(csv-parser)
Non-CMake (define the macro before any csv-parser header)
#define CSV_ENABLE_THREADS 0
#include "csv.hpp"
Single-threaded mode is useful for embedded targets, environments where std::thread is unavailable, and WebAssembly builds without pthreads. The public API is unchanged; parsing simply runs synchronously on the caller's thread.
Emscripten / WebAssembly
On Emscripten, CSV_ENABLE_THREADS is forced off and memory-mapped parsing is replaced by the stream-based parser. The filename constructor (CSVReader("file.csv")) still works—it opens an std::ifstream internally instead of using mmap.
Emscripten builds support the same explicit-error APIs with exceptions disabled. CMake no longer forces exception handling on; use the compiler settings appropriate for the application.
Single Header
📥 Download csv.hpp — Available on GitHub Pages
Or copy the URL:
https://vincentlaucsb.github.io/csv-parser/csv.hpp
- The file is automatically generated and deployed on every commit to
master, ensuring you always have the latest version - If you need a pinned version, check the Releases page
Please see the single_header project if you are interested in using the same C++ amalgamator this library uses. It is a Clang-backed executable that supports stitching (collapsing a method's declaration and implementation), namespace collapsing, #include hoisting/deduplication and other optimizations.
CMake Instructions
If you're including this in another CMake project, you can simply clone this repo into your project directory, and add the following to your CMakeLists.txt:
# Optional: disable background parsing threads
# set(CSV_ENABLE_THREADS OFF)
add_subdirectory(csv-parser)
# ...
add_executable(<your program> ...)
target_link_libraries(<your program> csv)
csv-parser respects the normal CMake CMAKE_CXX_STANDARD variable. If no
standard is provided, it defaults to C++20. The project-specific
CSV_CXX_STANDARD option is also supported as an explicit override:
CSV_CXX_STANDARD, when setCMAKE_CXX_STANDARD, when set- C++20 by default
For example:
set(CMAKE_CXX_STANDARD 17)
add_subdirectory(csv-parser)
or, if you want the csv-parser subtree to use a specific standard regardless of the parent project default:
set(CSV_CXX_STANDARD 11)
add_subdirectory(csv-parser)
Avoid cloning with FetchContent
Don't want to clone? No problem. There's also a simple example documenting how to use CMake's FetchContent module to integrate this library.
Bazel Instructions
This library is available on the Bazel Central Registry. To use it:
- Add the desired version from the Bazel Central Registry to your project's
MODULE.bazel:bazel_dep(name = "csv-parser", version = "1.2.3") - Add
"@csv-parser"to thedeps = []section of yourcc_libraryorcc_binarybuild rule. - Include the
csv.hppheader in your project.
Python Bindings
Experimental Python bindings live under python/. See
python/README.md for build instructions, API notes, and
benchmarks.
Features & Examples
Reading an Arbitrarily Large File (with Iterators)
With this library, you can easily stream over a large file without reading its entirety into memory.
C++ Style
# include "csv.hpp"
using namespace csv;
...
CSVReader reader("very_big_file.csv");
for (const auto& row : reader) { // Input iterator
for (const auto& field : row) {
// By default, get<>() produces a std::string.
// A more efficient get<string_view>() is also available, where the resulting
// string_view is valid as long as the parent CSVRow is alive
std::cout << field.get<>() << ...
}
}
...
Old-Fashioned C Style Loop
...
CSVReader reader("very_big_file.csv");
CSVRow row;
while (reader.read_row(row)) {
// Do stuff with row here
}
...
⚠️ IMPORTANT - Iterator Type and Memory Safety:
CSVReader::iterator is an input iterator (std::input_iterator_tag), NOT a forward iterator.
This design enables streaming large CSV files (50+ GB) without loading them entirely into memory, but may fail with some standard algorithms that require forward iterators.
If you need to get around this, I suggest either loading all rows into an STL container, e.g. std::vector<CSVRow>, or using the DataFrame class which supports row and column random access.
Use const auto& for read-only row and field loops. Field queries and conversions
are logically const: they lazily cache parsing results without changing the CSV
text or its interpretation. auto row and auto field also work when you want
local values; copying a row shares its backing storage without copying CSV text.
Reverse traversal through row.rbegin()/rend() works since C++11; standard
reverse adaptors and std::views::reverse are supported in C++20 and later.
See the field iteration guide for lifetimes,
iterator categories, and migration details.
Memory-Mapped I/O and Streams
When passing in a file path to CSVReader, memory-mapped I/O is used as it is the most performant.
However, most finite streams implementing std::istream, such as std::stringstream and std::ifstream, are supported as well as non-seekable streams. CSVReader is capable of taking a stream by reference, although it is recommended to pass in an owning std::unique_ptr<std::istream> for memory safety.
Both memory-mapped and std::istream paths benefit from having a background parsing thread, unless disabled.
CSVFormat format;
// custom formatting options go here
CSVReader mmap("some_file.csv", format);
std::unique_ptr<std::istream> infile_ptr(new std::ifstream("some_file.csv", std::ios::binary));
CSVReader ifstream_reader(std::move(infile_ptr), format);
std::stringstream my_csv;
CSVReader sstream_reader(my_csv, format);
Indexing by Column Names
Retrieving values using a column name string is a cheap, constant time operation with EXACT matching; with CASE_INSENSITIVE, the key is normalized before lookup.
# include "csv.hpp"
using namespace csv;
...
// Optional: pass in a format to customize lookup behavior
// Defaults to EXACT matching
CSVFormat format;
format.column_names_policy(ColumnNamePolicy::CASE_INSENSITIVE);
CSVReader reader("very_big_file.csv", format);
double sum = 0;
for (const auto& row : reader) {
// Note: Can also use index of column with [] operator
sum += row["Total Salary"].get<double>();
}
...
Numeric, Boolean, and Timestamp Conversions
CSV fields are heterogeneous, and this library provides several conversion APIs besides treating everything as a string.
These conversions are powered by classify_scalar, a separately maintained scalar classification library with its own test suite, configurable scalar grammars, and benchmarking notes. Use it directly if you want csv-parser's scalar behavior outside CSV parsing, or if you want to define a related classification policy for another data format.
For the full conversion contract, see the Scalar Conversion Reference.
Type checking is performed on conversions to prevent undefined behavior and integer overflow. Negative numbers cannot be blindly converted to unsigned integer types.
| API | Behavior | Notes |
|---|---|---|
get<T>() |
On success, returns T. On failure, throws std::runtime_error. |
Supports integral, floating point, bool, and std::chrono targets. |
try_get<T>(out) |
On success, writes out and returns true. On failure, returns false. |
Non-throwing equivalent to get<T>(). |
std::optional<T> value = field |
On success, returns a populated optional. On failure, returns std::nullopt. |
Uses the same conversion rules as try_get<T>(). |
field.as<T>() |
On success, returns std::expected<T, CSVConversionError>. On failure, returns std::unexpected(CSVConversionError). |
Requires std::expected availability; use when callers need a structured conversion error such as not-a-number, overflow, float-to-int, or negative-to-unsigned. |
try_parse_hex<T>(out) |
On success, writes an integral T and returns true. On failure, returns false. |
Allows hex with or without the 0x prefix. |
try_parse_decimal(out, decimal_symbol) |
On success, writes long double and returns true. On failure, returns false. |
Parses decimal numbers that use a non-. decimal separator. |
try_parse_timestamp<T>(out) |
On success, writes a timestamp/duration target and returns true. On failure, returns false. |
uint64_t Unix timestamps and std::chrono targets work in all supported C++ versions. |
Additional conversion details:
| Target | Supp
