r/cprogramming • u/giorgoskir5 • Aug 18 '26
I am open-sourcing csv.h a single-header CSV parser written in pure C99
For my thesis I had to read a lot of big CSV files in C and I couldn't really find a parser I wanted to use. The main C one is LGPL and comes with a whole build system, and everything else I found was C++. So I ended up writing my own. Now that im done with the thesis i cleaned it up properly , seperated it from the rest of the thesis code, and decided to standalone push it on GitHub.
It's one file. You copy csv.h into your project and that's it, nothing to link, no dependencies. It doesn't allocate memory, the fields just point into your own buffer, and you can run through files of any size a chunk at a time.
Honestly I spent way more time testing it than writing it. It passes csv-spectrum and I compared the output against Python's csv module on a few thousand files/
Check it out here -> https://github.com/GeorgeKiritsis/Csv.h
If someone has time to look at the API and tell me what could change or be imrpoved, that would help a lot. Thanks a lot in advance
21
u/Zirias_FreeBSD Aug 19 '26
Yeah, that does look very nice at a first glance. š
But -- please don't get this as a criticism of your code, it isn't! -- I really don't get this "header-only hype". I see this mostly came from C++ where it makes sense for the most generic stuff, if your lib is all templates. But why in C? If it's not all macros (and that's rare), there's always some trickery involved to build the actual implementation. Every time I use some "header-only lib" in my projects, I end up adding an extra translation unit for the implementation of that lib, because it doesn't naturally fit anywhere else and I don't want the clutter to leak.
I'd very much prefer a classic lib. Add at the least some super-simple build for a static archive (
.a), including that shouldn't be an issue for anyone. For smaller projects, building a shared lib can be considered optional indeed.Even if you dismiss the "classic" advantages of libs (like e.g. avoiding unnecessary rebuilds) for obvious reasons related to modern hardware, I very much prefer to read code that's clearly organized in multiple files. It's much easier to dive in that way. Sure, you could achieve something similar with a bunch of
#includedirectives as well, but again, why? I really don't see the disadvantage of building and linking a static lib. And if you ever need it, adding a build for a shared lib typically isn't too problematic.9
u/thebatmanandrobin Aug 19 '26
I'm sure this code worked for your explicit use case, and the "testing" you did was what's called "negative testing" .. that is, you tested your code against your specific case and fixed your code around that, instead of actually doing a full battery of tests for CSV parsing (try throwing a CSV that's UTF-16 or UTF-32 encoded at your "library" .. what does it do?)
I've gone through your code, and while it is clean, documented and seemingly non-AI generated (all great positives), its use is extremely limited and there are a lot of issues with it; take a look at your
CSV_ARRAY_LENmacro .. what does it do if you pass in a pointer to it???Not only are there a ton of "macro magic" issues, you don't use standard types (outside of
size_t), there's some confusing nomenclature and, as one commenter pointed out, the "header only" approach doesn't really work in C; what if I wanted a multi-threaded ability of this to munch away on a really large file across multiple TU's?? I'd have to initialize it multiple times with separate buffers and more (an absolute non-starter for something like an embedded environment).Plus, to even "use" your header, I absolutely must define
CSV_IMPLEMENTATION... why????Additionally to that, your parser is a basic state machine and makes a lot of assumptions about the data being passed in, and there are a few line counting bugs among some other issues including some obvious UB issues with your pointer handling ... again, things you probably "worked around" through building this specifically for the data sets you have and used this on.
All that is to say that there is a reason that some of those CSV libraries that you mention are so "large"; they're RFC 4180 compliant and can handle many things yours can't (like NULL bytes in a file, just to name one thing). Text parsing (e.g. CSV) and date/time parsing are some of the most complex and annoying CS problems that exist ...
I can appreciate your effort and work (I've been doing C and C++ for over 25 years now), and if I were to be hiring a Jr. SE, I'd absolutely consider you because of this single file ... but I would 100% scrutinize your choices and absolutely not consider you for anything more than a Jr. position because of this.
That's not a dig in any way and actually a compliment .. Engineers are brutal .. for very good reasons. So take what's said as a compliment, and if you wish to push this out to the world, I would advise that you specify that your parser is in-fact not RFC 4180 compliant and that it's purely a research project .. IANAL but "implied warranty" only goes so far, and putting your legal name on things can open you up to law suits; no matter how frivolous, you still have to go through the process .. but being able to shut it down at the start is even better.
Good luck!
4
u/catbrane Aug 19 '26
This looks nice, and thank you for releasing this. But I would never use a header-only library for anything serious in C.
What if you find a bug or add a useful feature? Now everyone who copy-pasted your header into their project has to do a manual copy-paste again, or start maintaining their own fork and patch it.
Moreover, because you have no defined API (no public / private split), users may start to depend on things you did not intend to be immutable. If you fix a bug and release a new version, it might well not be a simple copy-paste job. Your users may have changes to make, and that's inevitably going to introduce bugs in their code.
All non-trivial projects have proper build systems, and adding a dependency is a one line change. Copy-pasting an extra file is more effort, and more continuing effort, endlessly into the future. Header-only libraries create tech debt.
Make a classic library, with a defined API, semantic versioning, a proper build system, and then package it. Now it's easy to use and everyone gets patches, fixes, and updates automatically, with breaking API changes flagged up for them.
2
u/fsteff Aug 19 '26
At a quick glance this looks really useful.
Good job! Thank you!
2
u/JaseciLabs Aug 19 '26
Single-header, no allocation, fields pointing into your own buffer, this is exactly the shape a C library should take when you don't want to hand callers a dependency tree. Worth adding a short note in the README about what encoding/line-ending edge cases you've tested (quoted fields with embedded commas, CRLF vs LF, BOM), since that's usually where "I wrote my own CSV parser" projects get their first real bug reports.
1
u/Zectbumo Aug 19 '26
GPT says: Bug: CR-only line endings break comments and
skip_lines. The parser explicitly supports bare\ras a record terminatorāthe test suite includes"a\rb\r"and expects two records. Butcsv__skip_noise()finds the end of comment lines and skipped preamble lines usingmemchr(..., '\n', ...)only. It never searches for\r.So this should parse one record:
but the current comment path sees no
\n, reaches final input, and treats the entire remaining document as the comment. You get noa,brow. The same bug exists with:The fix is to make the noise skipper locate the earliest
\ror\n, then use the existingcsv__eat_eol(). That helper already correctly handles\r,\n,\r\n, and a CRLF split across streaming buffers.1
u/waterkip Aug 18 '26
Maybe have a look at Text::CSV_XS. That's my goto thing when I want/have to deal with CSV.Ā
4
u/ACRM64 Aug 19 '26
I agree with u/Zirias_FreeBSD I haven't tried using it, but in general the code looks good, but I also don't get the idea of putting it all in a header file.
I've been a C programmer for 40 years and, as a result, developed a lot of preferences as to how things are done, so please take the following as suggestions of how I like to do things...
#define), variable types(typedef) and global variables you use and nothing else.for()loops, but otherwise, it makes code much clearer if you use something more informative. For example, incsv_opts_default(void), why not useoptsinstead ofo? In many functionsreaderinstead ofr.I'm looking forward to trying out the code which I see is still under active development!
2
u/Sorry_Difficulty_250 Aug 18 '26
Cool!
1
u/vip17 Aug 19 '26
Nice documentation. What I expect from a parser is usually std::string_view for non-copy sharing, and SIMD for accelration, both of which are mentioned in your README
1
u/Zectbumo Aug 19 '26
GPT says: Optimization: make
csv_table_load()parse its owned file buffer in place.csv_table_parse()currently allocates an arena equal to the entire CSV size, setsCSV_FLAG_KEEP_SCRATCH, and parses throughcsv_reader_init_buf(). So an N-byte file gets an additional N-byte scratch allocation before cell/row metadata is considered. Butcsv_table_load()has already allocated and owns a mutablebufcontaining the entire file; after parsing it stores that buffer int->text. Despite owning it, it currently calls the const/borrowedcsv_table_parse()path. The library already has exactly the mechanism needed:csv_reader_init_mut(&rd, opts, buf, len);In-place mode requires no scratch buffer and resolves escaped quotes directly inside the owned input; its field pointers remain valid as long as that buffer exists.I would factor the cell/row collection loop out of
csv_table_parse()into an internal helper, then havecsv_table_parse()use the existing const+arena path whilecsv_table_load()usescsv_reader_init_mut(). That optimization would eliminate one allocation equal to the entire file size forcsv_table_load()and avoid copying escaped field contents into the arena. For a 1 GB CSV, that's roughly 1 GB of allocation eliminated, while leaving the public borrowedcsv_table_parse()semantics unchanged.