Skip to Content
Course content

234: Practice Exercise: Building a Small CSV Parser

Click on the "Edit" button in the top corner of the screen to edit your slide content.

When you first start thinking about parsing Comma Separated Values (CSV) in C, your instinct is probably to reach for strtok(). It seems like the perfect tool: you give it a string and a delimiter, and it chops the string up for you. I've seen countless developers jump straight to this, and it always leads to the same wall.

The trap of thinking strtok() handles CSVs

The problem is that strtok() is far too blunt for real-world CSVs. It treats every single instance of your delimiter as a break point. But in actual CSV files, we use double quotes to escape delimiters. Imagine you're parsing a list of addresses:

John Doe, "New York, NY", 10001

If you use strtok(line, ","), it's going to split that second field right in the middle of the city and state. You'll end up with "New York" and " NY" as two separate columns, which completely breaks your data alignment. Plus, strtok() modifies the original string by inserting null terminators, which can be a nightmare if you need to keep the original line intact for logging or auditing.

Walking the string with a quote flag

To do this right, you have to stop thinking about "splitting" and start thinking about "scanning." You need a way to track whether you are currently "inside" a quoted block. I usually handle this with a simple boolean flag (or an integer if you're using an older C standard).

As you iterate through the string character by character, you check for quotes. If you hit a ", you toggle your in_quotes flag. Now, when you encounter a comma, you only treat it as a field separator if in_quotes is false. This allows the parser to ignore commas that are part of the actual data.

char *ptr = line;
int in_quotes = 0;
while (*ptr) {
    if (*ptr == '"') {
        in_quotes = !in_quotes;
    } else if (*ptr == ',' && !in_quotes) {
        // This is a real delimiter!
    }
    ptr++;
}

Managing the resulting buffers

Once you've identified where a field starts and ends, you have to decide where that data goes. Since C doesn't have a native "string" type that grows automatically, you'll likely use a fixed-size buffer for each field. Just be careful—if a CSV field exceeds your buffer size, you're looking at a classic buffer overflow. I recommend using strncpy or manually tracking the index to ensure you never write past the end of your allocated memory.

Also, don't forget to strip the surrounding quotes from the final output. The user wants the value New York, NY, not "New York, NY". You can handle this by simply skipping the first and last characters of the field if they are quotes.




📋 Practical Task

Build a Quoted-Field CSV Row Processor

Your task is to write a program that processes a single line of CSV text and prints each field on a new line. Your parser must correctly handle fields that contain commas wrapped in double quotes.

Requirements:

  • Create a function void parse_csv_line(char *line).
  • The function should iterate through the string and print each field.
  • If a field is wrapped in quotes (e.g., "Hello, World"), the quotes should be removed in the final output, but the comma inside should be preserved.
  • Test your code with the following input string: 101, "Widget, Deluxe", 25.99, "Available".

Expected Output:

101
Widget, Deluxe
25.99
Available
Rating
0 0

There are no comments for now.

to be the first to leave a comment.