Programming Search⌘K

Taskcore

Read a CSV file

Also called parse a CSV file, read comma-separated values, load a CSV file into records, read a CSV file with a header.

Read a CSV file with a header line into one record for each line, with quoted fields that hold commas, double quotes and line breaks, as RFC 4180 defines them.

Task

Read a CSV file with a header line. Return one record for each line after the header. A record maps each name of the header to the field in the same column.

The format is the one that RFC 4180 (section 2) defines:

  • Commas separate the fields. A line break ends a record. The last record can have a line break or not.
  • A field that holds a comma, a double quote or a line break is enclosed in double quotes. A double quote inside such a field is written twice, so "She said ""hi""." is the field She said "hi"..
  • Spaces are part of a field. The solution does not trim them.
  • Each record has the same number of fields as the header.

RFC 4180 uses CRLF as the line break. Many files use LF, so the solution accepts both. A line break inside a quoted field is returned as LF, so the result is the same for both kinds of file. The solution reads the file as UTF-8 and removes a byte order mark at the start, because some programs write one.

The solution skips an empty line. So an empty file, a file with only a header, and a file with an empty last line give no extra records. A file with one column must write an empty field as "", because an empty line gives no record.

The solution reports an error and returns no records in three cases: a record has more or fewer fields than the header (field-count), a quoted field has no closing quote or has text after its closing quote (bad-quote), and the file does not exist (not-found).

Solutions

The standard libraries of Python and Go have a CSV reader. JavaScript, TypeScript, Java, C#, Rust, C and C++ have none, so their solutions hold a small parser of RFC 4180, with a test for each case. The parser is the same state machine in each language:

  1. At the start of a record, an empty line is skipped.
  2. A field that starts with " is quoted. A pair "" gives one ", a CRLF gives LF, and any other character is part of the field. A single " ends the field. After it, the next character must be a comma, a line break or the end of the text, or the parser reports bad-quote. The end of the text inside the quotes is also bad-quote.
  3. Any other field runs up to the next comma, line break or the end of the text.
  4. A comma starts the next field of the same record. Anything else ends the record.

The parser works on whole text in memory. The contract limits each field to 100000 characters.

  • Python. csv.reader reads a file that is opened with encoding="utf-8-sig" and newline="". The utf-8-sig codec skips a byte order mark. Without newline="", the csv module cannot read a line break inside a quoted field correctly. strict=True makes the reader raise csv.Error on a bad quote. The default is False. The reader gives an empty list for an empty line, and the code skips it. The code checks the number of fields itself and raises csv.Error. It changes a CRLF in a field to LF.
  • JavaScript and TypeScript (Node.js). readFile with "utf8" reads the text, and the code removes a leading U+FEFF. parseCsv is the state machine. Object.fromEntries makes each record, and it creates each name as an own property of the object. So a header name such as __proto__ is a normal key. The error is a CsvError with a kind field. The TypeScript file adds types only.
  • Java. Files.readString decodes the file as UTF-8. The code removes a leading U+FEFF and runs the state machine. Each record is a LinkedHashMap, so the names keep the order of the header. CsvException extends IOException and has a kind().
  • C#. File.ReadAllText detects a byte order mark and does not return it. The code runs the state machine and makes a Dictionary<string, string> for each record. CsvException extends FormatException. The class TextFieldParser in Microsoft.VisualBasic.FileIO reads CSV, but it changes a field that holds an empty line (see the pitfalls).
  • Go. csv.NewReader from encoding/csv reads the records. It removes a carriage return before a newline, also inside a quoted field, and it ignores blank lines. With FieldsPerRecord at 0, the reader takes the number of fields from the first record, and a record with another number gives an error that wraps csv.ErrFieldCount. With LazyQuotes false, a bad quote gives an error that wraps csv.ErrQuote. The code removes a byte order mark with bufio.Reader.Peek before the CSV reader sees it.
  • Rust. fs::read_to_string returns an error if the file is not UTF-8. The code strips a leading U+FEFF and runs the state machine on the bytes. Each delimiter is an ASCII byte, so each field is still valid UTF-8. CsvError is an enum with Io, FieldCount and BadQuote.
  • C. fopen with mode "rb" and fread read the whole file. The flag b has no effect on POSIX, and on Windows it stops the change of line breaks. The parser makes a struct csv_table with the header and an array of fields for each record, in the order of the header. csv_field finds a field by name. read_csv returns an enum csv_status, and csv_table_free frees the table.
  • C++. An std::ifstream in binary mode and std::istreambuf_iterator read the file into a std::string. The parser works on a std::string_view. Each record is a std::map<std::string, std::string>. A bad file throws csv_error, and a file that cannot be opened throws std::ios_base::failure.

Bash has no CSV parser, and the word splitting of the shell cannot read a quoted field. So this page has no Bash solution. The file matrix.yaml records this.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl. Each case reads one file from fixtures/. The file .gitattributes marks the fixtures as -text, so Git does not change their line breaks.

  • crlf and no-final-newline: the same records as simple, with CRLF line breaks, and with no line break at the end.
  • quoted-comma, escaped-quote and quoted-header: "Lovelace, Ada" is one field. "" inside quotes is one ". A header name can be quoted too.
  • newline-in-field, crlf-in-field and blank-line-in-field: a quoted field holds a line break, a CRLF or an empty line. A reader that reads one line at a time splits the record. The result has LF in each case.
  • empty-last-line and blank-lines: empty lines between and after the records give no record.
  • empty-fields and quoted-empty: ,, gives three empty fields. "" gives one empty field, and that is the only way to write an empty field in a file with one column.
  • spaces: x , y keeps its spaces.
  • header-only and empty-file: no records.
  • bom: the first name is name, with no U+FEFF before it.
  • non-ascii: Zürich and 東京 in UTF-8.

The cases in cases/errors.jsonl must give an error. The toolchain does not load this file yet, so the test files hold these cases by name: a record with too few fields, a record with too many fields, a quote with no end, text after a closing quote, and a missing file.

Pitfalls

  • Splitting on commas breaks a quoted field. A split on , or on \n does not know about quotes. It is correct only for files that have no quotes. Use a CSV reader or a parser of the format:

This code runs but gives a wrong answer on purpose.

const line = '"Lovelace, Ada",1815';
console.log(line.split(","));
Output
[ '"Lovelace', ' Ada"', '1815' ]
  • Python accepts bad quotes by default. With the default strict=False, csv.reader reads text after a closing quote into the field, and a quote with no end takes the rest of the file into one field. Give strict=True:

This code runs but gives a wrong answer on purpose.

import csv
import io

for text in ['a,"b"c\n', 'a,"b\nc,d\n']:
    print(list(csv.reader(io.StringIO(text, newline=""))))
    try:
        list(csv.reader(io.StringIO(text, newline=""), strict=True))
    except csv.Error as e:
        print("csv.Error:", e)
Output
[['a', 'bc']]
csv.Error: ',' expected after '"'
[['a', 'b\nc,d\n']]
csv.Error: unexpected end of data
  • csv.DictReader does not check the number of fields. A missing field becomes restval, which is None by default. Extra fields go into a list under the key restkey, which is also None by default. Check the length of each row, as the Python solution does:

This code runs but gives a wrong answer on purpose.

import csv
import io

text = "name,age\nAda\nAlan,41,London\n"
for record in csv.DictReader(io.StringIO(text, newline="")):
    print(record)
Output
{'name': 'Ada', 'age': None}
{'name': 'Alan', 'age': '41', None: ['London']}
  • Python limits the size of a field. csv.field_size_limit() returns the limit, and a longer field raises csv.Error. A file with a large text field fails with the default:

This code runs but gives a wrong answer on purpose.

import csv
import io

print(csv.field_size_limit())
text = "note\n" + "x" * 200_000 + "\n"
try:
    list(csv.reader(io.StringIO(text, newline="")))
except csv.Error as e:
    print("csv.Error:", e)
Output
131072
csv.Error: field larger than field limit (131072)
  • The byte order mark stays in the first name. Node.js readFile with "utf8" returns U+FEFF as the first character. The first name of the header is then U+FEFF and name, so a lookup of name finds no field:

This code runs but gives a wrong answer on purpose.

import { readFile, writeFile } from "node:fs/promises";

await writeFile("people.csv", "\uFEFFname,age\nAda,36\n");
const text = await readFile("people.csv", "utf8");
console.log(text.codePointAt(0).toString(16), text.startsWith("name"));
Output
feff false
  • TextFieldParser drops an empty line inside a quoted field. In .NET, TextFieldParser.ReadFields skips blank lines. It also removes an empty line that is inside quotes, so the field changes:

This code runs but gives a wrong answer on purpose.

using Microsoft.VisualBasic.FileIO;

File.WriteAllText("notes.csv", "id,note\n1,\"one\n\ntwo\"\n");
using var parser = new TextFieldParser("notes.csv");
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
    string[] fields = parser.ReadFields()!;
    Console.WriteLine(string.Join(" | ", fields.Select(f => f.Replace("\n", "\\n"))));
}
Output
id | note
1 | one\ntwo

Code

The build runs the native tests of each language in a pinned toolchain.

read_csv.pyI0tests passRawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-csv-file/.

import csv
import os


def read_csv(path: str | os.PathLike[str]) -> list[dict[str, str]]:
    """Read a CSV file with a header line into one dict for each record.

    Raise csv.Error for a bad quote or for a record with the wrong number of
    fields.
    """
    # utf-8-sig removes a byte order mark. newline="" gives the line breaks
    # inside quoted fields to the csv module unchanged.
    with open(path, encoding="utf-8-sig", newline="") as file:
        # strict=True raises csv.Error on a bad quote. The default accepts it.
        reader = csv.reader(file, strict=True)
        header = next(reader, None)
        while header == []:
            header = next(reader, None)
        if header is None:
            return []
        records = []
        for row in reader:
            if not row:
                continue  # an empty line
            if len(row) != len(header):
                raise csv.Error(f"line {reader.line_num}: {len(row)} fields, want {len(header)}")
            records.append({name: field.replace("\r\n", "\n") for name, field in zip(header, row)})
        return records
test_read_csv.py 63 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-csv-file/.

import csv
from pathlib import Path

import pytest

from read_csv import read_csv

ADA_ALAN = [{"name": "Ada", "age": "36"}, {"name": "Alan", "age": "41"}]

CASES = {
    "simple": (b"name,age\nAda,36\nAlan,41\n", ADA_ALAN),
    "crlf": (b"name,age\r\nAda,36\r\nAlan,41\r\n", ADA_ALAN),
    "no-final-newline": (b"name,age\nAda,36\nAlan,41", ADA_ALAN),
    "quoted-comma": (b'name,born\n"Lovelace, Ada",1815\n', [{"name": "Lovelace, Ada", "born": "1815"}]),
    "escaped-quote": (b'id,quote\n1,"She said ""hi""."\n', [{"id": "1", "quote": 'She said "hi".'}]),
    "quoted-header": (b'"first name","last name"\nAda,Lovelace\n', [{"first name": "Ada", "last name": "Lovelace"}]),
    "newline-in-field": (b'id,address\n1,"12 High St\nLeeds"\n', [{"id": "1", "address": "12 High St\nLeeds"}]),
    "crlf-in-field": (b'id,address\r\n1,"12 High St\r\nLeeds"\r\n', [{"id": "1", "address": "12 High St\nLeeds"}]),
    "blank-line-in-field": (b'id,note\n1,"one\n\ntwo"\n', [{"id": "1", "note": "one\n\ntwo"}]),
    "empty-last-line": (b"a,b\n1,2\n\n", [{"a": "1", "b": "2"}]),
    "blank-lines": (b"a,b\n\n1,2\n\n\n3,4\n", [{"a": "1", "b": "2"}, {"a": "3", "b": "4"}]),
    "empty-fields": (b"a,b,c\n,,\n", [{"a": "", "b": "", "c": ""}]),
    "quoted-empty": (b'name\n""\n', [{"name": ""}]),
    "spaces": (b"a,b\n x , y \n", [{"a": " x ", "b": " y "}]),
    "header-only": (b"a,b\n", []),
    "empty-file": (b"", []),
    "bom": (b"\xef\xbb\xbfname,age\nAda,36\n", [{"name": "Ada", "age": "36"}]),
    "non-ascii": (
        "city,country\nZürich,Schweiz\n東京,日本\n".encode(),
        [{"city": "Zürich", "country": "Schweiz"}, {"city": "東京", "country": "日本"}],
    ),
}

INVALID = {
    "too-few-fields": b"a,b\n1\n",
    "too-many-fields": b"a,b\n1,2,3\n",
    "unclosed-quote": b'a,b\n1,"two\n',
    "text-after-quote": b'a,b\n1,"two"x\n',
}


@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, name: str) -> None:
    data, want = CASES[name]
    path = tmp_path / "input.csv"
    path.write_bytes(data)
    assert read_csv(path) == want


@pytest.mark.parametrize("name", INVALID)
def test_invalid(tmp_path: Path, name: str) -> None:
    path = tmp_path / "input.csv"
    path.write_bytes(INVALID[name])
    with pytest.raises(csv.Error):
        read_csv(path)


def test_missing(tmp_path: Path) -> None:
    with pytest.raises(FileNotFoundError):
        read_csv(tmp_path / "missing.csv")
read_csv.cppI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

// The C++ standard library has no CSV reader, so this file has a small parser of RFC 4180.

#include "read_csv.hpp"

#include <fstream>
#include <iterator>

namespace {

// Returns the length of the line break at i: 1 for LF, 2 for CRLF, 0 for none.
std::size_t line_break(std::string_view s, std::size_t i) {
    if (i < s.size() && s[i] == '\n') {
        return 1;
    }
    return i + 1 < s.size() && s[i] == '\r' && s[i + 1] == '\n' ? 2 : 0;
}

}  // namespace

std::vector<std::vector<std::string>> parse_csv(std::string_view s) {
    std::vector<std::vector<std::string>> records;
    std::size_t i = 0;
    while (i < s.size()) {
        if (std::size_t empty = line_break(s, i); empty > 0) {
            i += empty;
            continue;
        }
        std::vector<std::string> record;
        for (;;) {
            std::string field;
            if (i < s.size() && s[i] == '"') {
                ++i;
                for (;;) {
                    if (i >= s.size()) {
                        throw csv_error(csv_error::kind::bad_quote, "a quoted field has no closing quote");
                    }
                    if (s[i] == '"') {
                        if (i + 1 >= s.size() || s[i + 1] != '"') {
                            break;
                        }
                        field += '"';
                        i += 2;
                    } else if (line_break(s, i) == 2) {
                        field += '\n';  // CRLF inside quotes becomes LF.
                        i += 2;
                    } else {
                        field += s[i++];
                    }
                }
                ++i;  // the closing quote
                if (i < s.size() && s[i] != ',' && line_break(s, i) == 0) {
                    throw csv_error(csv_error::kind::bad_quote, "text after the closing quote of a field");
                }
            } else {
                std::size_t start = i;
                while (i < s.size() && s[i] != ',' && line_break(s, i) == 0) {
                    ++i;
                }
                field = s.substr(start, i - start);
            }
            record.push_back(std::move(field));
            if (i >= s.size() || s[i] != ',') {
                break;
            }
            ++i;
        }
        i += line_break(s, i);
        records.push_back(std::move(record));
    }
    return records;
}

std::vector<std::map<std::string, std::string>> read_csv(const std::filesystem::path& path) {
    std::ifstream in(path, std::ios::binary);
    if (!in) {
        throw std::ios_base::failure("cannot open " + path.string());
    }
    std::string text(std::istreambuf_iterator<char>(in), {});
    std::string_view view = text;
    if (view.starts_with("\xEF\xBB\xBF")) {  // the UTF-8 byte order mark
        view.remove_prefix(3);
    }
    auto rows = parse_csv(view);
    std::vector<std::map<std::string, std::string>> records;
    for (std::size_t n = 1; n < rows.size(); ++n) {
        if (rows[n].size() != rows[0].size()) {
            throw csv_error(csv_error::kind::field_count, "record " + std::to_string(n) + " has " +
                                                              std::to_string(rows[n].size()) + " fields, want " +
                                                              std::to_string(rows[0].size()));
        }
        std::map<std::string, std::string> record;
        for (std::size_t k = 0; k < rows[0].size(); ++k) {
            record.emplace(rows[0][k], std::move(rows[n][k]));
        }
        records.push_back(std::move(record));
    }
    return records;
}
read_csv.hpp 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

#pragma once

#include <filesystem>
#include <map>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>

// The error for a file that is not valid CSV.
class csv_error : public std::runtime_error {
public:
    enum class kind { field_count, bad_quote };
    csv_error(kind k, const std::string& what) : std::runtime_error(what), kind_(k) {}
    [[nodiscard]] kind which() const noexcept { return kind_; }

private:
    kind kind_;
};

// Splits RFC 4180 text into records of fields. An empty line gives no record.
std::vector<std::vector<std::string>> parse_csv(std::string_view text);

// Returns one map for each record after the header, from each name to its field.
// Throws csv_error for text that is not valid CSV, and std::ios_base::failure if the file cannot be opened.
std::vector<std::map<std::string, std::string>> read_csv(const std::filesystem::path& path);
test_read_csv.cpp 92 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

#include <cstdio>
#include <fstream>
#include <string>
#include <vector>

#include "read_csv.hpp"

namespace {

using record = std::map<std::string, std::string>;

const std::filesystem::path input = "read_csv_input.csv";

void write(const std::string& data) {
    std::ofstream out(input, std::ios::binary);
    out << data;
}

struct test_case {
    const char* name;
    std::string data;
    std::vector<record> want;
};

int failed = 0;

void check(bool ok, const char* name) {
    if (!ok) {
        std::fprintf(stderr, "FAIL %s\n", name);
        ++failed;
    }
}

}  // namespace

int main() {
    const std::vector<record> ada_alan = {{{"name", "Ada"}, {"age", "36"}}, {{"name", "Alan"}, {"age", "41"}}};
    const std::vector<test_case> cases = {
        {"simple", "name,age\nAda,36\nAlan,41\n", ada_alan},
        {"crlf", "name,age\r\nAda,36\r\nAlan,41\r\n", ada_alan},
        {"no-final-newline", "name,age\nAda,36\nAlan,41", ada_alan},
        {"quoted-comma", "name,born\n\"Lovelace, Ada\",1815\n", {{{"name", "Lovelace, Ada"}, {"born", "1815"}}}},
        {"escaped-quote", "id,quote\n1,\"She said \"\"hi\"\".\"\n", {{{"id", "1"}, {"quote", "She said \"hi\"."}}}},
        {"quoted-header", "\"first name\",\"last name\"\nAda,Lovelace\n", {{{"first name", "Ada"}, {"last name", "Lovelace"}}}},
        {"newline-in-field", "id,address\n1,\"12 High St\nLeeds\"\n", {{{"id", "1"}, {"address", "12 High St\nLeeds"}}}},
        {"crlf-in-field", "id,address\r\n1,\"12 High St\r\nLeeds\"\r\n", {{{"id", "1"}, {"address", "12 High St\nLeeds"}}}},
        {"blank-line-in-field", "id,note\n1,\"one\n\ntwo\"\n", {{{"id", "1"}, {"note", "one\n\ntwo"}}}},
        {"empty-last-line", "a,b\n1,2\n\n", {{{"a", "1"}, {"b", "2"}}}},
        {"blank-lines", "a,b\n\n1,2\n\n\n3,4\n", {{{"a", "1"}, {"b", "2"}}, {{"a", "3"}, {"b", "4"}}}},
        {"empty-fields", "a,b,c\n,,\n", {{{"a", ""}, {"b", ""}, {"c", ""}}}},
        {"quoted-empty", "name\n\"\"\n", {{{"name", ""}}}},
        {"spaces", "a,b\n x , y \n", {{{"a", " x "}, {"b", " y "}}}},
        {"header-only", "a,b\n", {}},
        {"empty-file", "", {}},
        {"bom", "\xEF\xBB\xBFname,age\nAda,36\n", {{{"name", "Ada"}, {"age", "36"}}}},
        {"non-ascii", "city,country\nZürich,Schweiz\n東京,日本\n",
         {{{"city", "Zürich"}, {"country", "Schweiz"}}, {{"city", "東京"}, {"country", "日本"}}}},
    };
    for (const auto& tc : cases) {
        write(tc.data);
        check(read_csv(input) == tc.want, tc.name);
    }
    const std::vector<std::pair<std::string, csv_error::kind>> invalid = {
        {"a,b\n1\n", csv_error::kind::field_count},
        {"a,b\n1,2,3\n", csv_error::kind::field_count},
        {"a,b\n1,\"two\n", csv_error::kind::bad_quote},
        {"a,b\n1,\"two\"x\n", csv_error::kind::bad_quote},
    };
    for (const auto& [data, kind] : invalid) {
        write(data);
        try {
            read_csv(input);
            check(false, data.c_str());
        } catch (const csv_error& e) {
            check(e.which() == kind, data.c_str());
        }
    }
    std::filesystem::remove(input);
    try {
        read_csv(input);
        check(false, "missing");
    } catch (const std::ios_base::failure&) {
    }
    if (failed > 0) {
        return 1;
    }
    std::puts("ok");
    return 0;
}
ReadCsv.javaI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

import java.io.IOException;
import java.io.Serial;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/** Reads a CSV file of RFC 4180 with a header line. */
public final class ReadCsv {
    private ReadCsv() {}

    /** The error for a file that is not valid CSV. kind is "field-count" or "bad-quote". */
    public static final class CsvException extends IOException {
        @Serial private static final long serialVersionUID = 1L;
        private final String kind;

        CsvException(String kind, String message) {
            super(message);
            this.kind = kind;
        }

        public String kind() {
            return kind;
        }
    }

    /** Returns one map for each record after the header, from each name to its field. */
    public static List<Map<String, String>> read(Path path) throws IOException {
        // readString decodes UTF-8 and throws on bytes that are not UTF-8.
        String text = Files.readString(path);
        if (text.startsWith("\uFEFF")) {
            text = text.substring(1);
        }
        List<List<String>> rows = parse(text);
        List<Map<String, String>> records = new ArrayList<>();
        if (rows.isEmpty()) {
            return records;
        }
        List<String> header = rows.getFirst();
        for (int n = 1; n < rows.size(); n++) {
            List<String> row = rows.get(n);
            if (row.size() != header.size()) {
                throw new CsvException("field-count",
                        "record " + n + " has " + row.size() + " fields, want " + header.size());
            }
            Map<String, String> record = new LinkedHashMap<>();
            for (int k = 0; k < row.size(); k++) {
                record.put(header.get(k), row.get(k));
            }
            records.add(record);
        }
        return records;
    }

    /** Returns the length of the line break at i: 1 for LF, 2 for CRLF, 0 for none. */
    private static int lineBreak(String text, int i) {
        if (i < text.length() && text.charAt(i) == '\n') {
            return 1;
        }
        if (i + 1 < text.length() && text.charAt(i) == '\r' && text.charAt(i + 1) == '\n') {
            return 2;
        }
        return 0;
    }

    /** Splits RFC 4180 text into records of fields. An empty line gives no record. */
    static List<List<String>> parse(String text) throws CsvException {
        List<List<String>> records = new ArrayList<>();
        int n = text.length();
        int i = 0;
        while (i < n) {
            int empty = lineBreak(text, i);
            if (empty > 0) {
                i += empty;
                continue;
            }
            List<String> record = new ArrayList<>();
            while (true) {
                StringBuilder field = new StringBuilder();
                if (i < n && text.charAt(i) == '"') {
                    i++;
                    while (true) {
                        if (i >= n) {
                            throw new CsvException("bad-quote", "a quoted field has no closing quote");
                        }
                        char c = text.charAt(i);
                        if (c == '"') {
                            if (i + 1 >= n || text.charAt(i + 1) != '"') {
                                break;
                            }
                            field.append('"');
                            i += 2;
                        } else if (lineBreak(text, i) == 2) {
                            field.append('\n'); // CRLF inside quotes becomes LF.
                            i += 2;
                        } else {
                            field.append(c);
                            i++;
                        }
                    }
                    i++; // the closing quote
                    if (i < n && text.charAt(i) != ',' && lineBreak(text, i) == 0) {
                        throw new CsvException("bad-quote", "text after the closing quote of a field");
                    }
                } else {
                    while (i < n && text.charAt(i) != ',' && lineBreak(text, i) == 0) {
                        field.append(text.charAt(i++));
                    }
                }
                record.add(field.toString());
                if (i >= n || text.charAt(i) != ',') {
                    break;
                }
                i++;
            }
            i += lineBreak(text, i);
            records.add(record);
        }
        return records;
    }
}
ReadCsvTest.java 87 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class ReadCsvTest {
    @TempDir Path dir;

    static final List<Map<String, String>> ADA_ALAN =
            List.of(Map.of("name", "Ada", "age", "36"), Map.of("name", "Alan", "age", "41"));

    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("simple", "name,age\nAda,36\nAlan,41\n", ADA_ALAN),
                Arguments.of("crlf", "name,age\r\nAda,36\r\nAlan,41\r\n", ADA_ALAN),
                Arguments.of("no-final-newline", "name,age\nAda,36\nAlan,41", ADA_ALAN),
                Arguments.of("quoted-comma", "name,born\n\"Lovelace, Ada\",1815\n",
                        List.of(Map.of("name", "Lovelace, Ada", "born", "1815"))),
                Arguments.of("escaped-quote", "id,quote\n1,\"She said \"\"hi\"\".\"\n",
                        List.of(Map.of("id", "1", "quote", "She said \"hi\"."))),
                Arguments.of("quoted-header", "\"first name\",\"last name\"\nAda,Lovelace\n",
                        List.of(Map.of("first name", "Ada", "last name", "Lovelace"))),
                Arguments.of("newline-in-field", "id,address\n1,\"12 High St\nLeeds\"\n",
                        List.of(Map.of("id", "1", "address", "12 High St\nLeeds"))),
                Arguments.of("crlf-in-field", "id,address\r\n1,\"12 High St\r\nLeeds\"\r\n",
                        List.of(Map.of("id", "1", "address", "12 High St\nLeeds"))),
                Arguments.of("blank-line-in-field", "id,note\n1,\"one\n\ntwo\"\n",
                        List.of(Map.of("id", "1", "note", "one\n\ntwo"))),
                Arguments.of("empty-last-line", "a,b\n1,2\n\n", List.of(Map.of("a", "1", "b", "2"))),
                Arguments.of("blank-lines", "a,b\n\n1,2\n\n\n3,4\n",
                        List.of(Map.of("a", "1", "b", "2"), Map.of("a", "3", "b", "4"))),
                Arguments.of("empty-fields", "a,b,c\n,,\n", List.of(Map.of("a", "", "b", "", "c", ""))),
                Arguments.of("quoted-empty", "name\n\"\"\n", List.of(Map.of("name", ""))),
                Arguments.of("spaces", "a,b\n x , y \n", List.of(Map.of("a", " x ", "b", " y "))),
                Arguments.of("header-only", "a,b\n", List.of()),
                Arguments.of("empty-file", "", List.of()),
                Arguments.of("bom", "\uFEFFname,age\nAda,36\n", List.of(Map.of("name", "Ada", "age", "36"))),
                Arguments.of("non-ascii", "city,country\nZürich,Schweiz\n東京,日本\n",
                        List.of(Map.of("city", "Zürich", "country", "Schweiz"), Map.of("city", "東京", "country", "日本"))));
    }

    Path write(String text) throws IOException {
        return Files.writeString(dir.resolve("input.csv"), text, StandardCharsets.UTF_8);
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void reads(String name, String text, List<Map<String, String>> want) throws IOException {
        assertEquals(want, ReadCsv.read(write(text)), name);
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource
    void invalid(String name, String text, String kind) throws IOException {
        Path path = write(text);
        ReadCsv.CsvException e = assertThrows(ReadCsv.CsvException.class, () -> ReadCsv.read(path));
        assertEquals(kind, e.kind(), name);
    }

    static Stream<Arguments> invalid() {
        return Stream.of(
                Arguments.of("too-few-fields", "a,b\n1\n", "field-count"),
                Arguments.of("too-many-fields", "a,b\n1,2,3\n", "field-count"),
                Arguments.of("unclosed-quote", "a,b\n1,\"two\n", "bad-quote"),
                Arguments.of("text-after-quote", "a,b\n1,\"two\"x\n", "bad-quote"));
    }

    @Test
    void missing() {
        assertThrows(NoSuchFileException.class, () -> ReadCsv.read(dir.resolve("missing.csv")));
    }
}
read_csv.cI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

// The C standard library has no CSV reader, so this file has a small parser of RFC 4180.

#include "read_csv.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// A growing array of bytes or of pointers.
struct bytes {
    char *p;
    size_t n, cap;
};

struct row {
    char **fields;
    size_t n, cap;
};

struct rows {
    struct row *p;
    size_t n, cap;
};

static bool push_byte(struct bytes *b, char c) {
    if (b->n + 1 >= b->cap) {
        size_t cap = b->cap ? 2 * b->cap : 64;
        char *p = realloc(b->p, cap);
        if (p == nullptr) {
            return false;
        }
        b->p = p;
        b->cap = cap;
    }
    b->p[b->n++] = c;
    b->p[b->n] = '\0';
    return true;
}

static bool push_field(struct row *r, char *field) {
    if (r->n == r->cap) {
        size_t cap = r->cap ? 2 * r->cap : 8;
        char **p = realloc(r->fields, cap * sizeof *p);
        if (p == nullptr) {
            return false;
        }
        r->fields = p;
        r->cap = cap;
    }
    r->fields[r->n++] = field;
    return true;
}

static bool push_row(struct rows *rs, struct row r) {
    if (rs->n == rs->cap) {
        size_t cap = rs->cap ? 2 * rs->cap : 16;
        struct row *p = realloc(rs->p, cap * sizeof *p);
        if (p == nullptr) {
            return false;
        }
        rs->p = p;
        rs->cap = cap;
    }
    rs->p[rs->n++] = r;
    return true;
}

static void free_row(struct row *r) {
    for (size_t i = 0; i < r->n; i++) {
        free(r->fields[i]);
    }
    free(r->fields);
}

static void free_rows(struct rows *rs) {
    for (size_t i = 0; i < rs->n; i++) {
        free_row(&rs->p[i]);
    }
    free(rs->p);
}

// Returns the length of the line break at i: 1 for LF, 2 for CRLF, 0 for none.
static size_t line_break(const char *s, size_t len, size_t i) {
    if (i < len && s[i] == '\n') {
        return 1;
    }
    return i + 1 < len && s[i] == '\r' && s[i + 1] == '\n' ? 2 : 0;
}

// Reads one field at *i into a new string in *out.
static enum csv_status parse_field(const char *s, size_t len, size_t *i, char **out) {
    struct bytes b = {0};
    if (!push_byte(&b, '\0')) { // an empty field is an empty string, not a null pointer
        return CSV_ERR_MEMORY;
    }
    b.n = 0;
    size_t j = *i;
    if (j < len && s[j] == '"') {
        j++;
        for (;;) {
            if (j >= len) {
                free(b.p);
                return CSV_ERR_BAD_QUOTE;
            }
            char c = s[j];
            size_t step = 1;
            if (c == '"') {
                if (j + 1 >= len || s[j + 1] != '"') {
                    break;
                }
                step = 2;
            } else if (line_break(s, len, j) == 2) {
                c = '\n'; // CRLF inside quotes becomes LF.
                step = 2;
            }
            if (!push_byte(&b, c)) {
                free(b.p);
                return CSV_ERR_MEMORY;
            }
            j += step;
        }
        j++; // the closing quote
        if (j < len && s[j] != ',' && line_break(s, len, j) == 0) {
            free(b.p);
            return CSV_ERR_BAD_QUOTE;
        }
    } else {
        while (j < len && s[j] != ',' && line_break(s, len, j) == 0) {
            if (!push_byte(&b, s[j++])) {
                free(b.p);
                return CSV_ERR_MEMORY;
            }
        }
    }
    *i = j;
    *out = b.p;
    return CSV_OK;
}

// Splits RFC 4180 text into records of fields. An empty line gives no record.
static enum csv_status parse_csv(const char *s, size_t len, struct rows *out) {
    struct rows rs = {0};
    size_t i = 0;
    while (i < len) {
        size_t empty = line_break(s, len, i);
        if (empty > 0) {
            i += empty;
            continue;
        }
        struct row r = {0};
        for (;;) {
            char *field = nullptr;
            enum csv_status st = parse_field(s, len, &i, &field);
            if (st == CSV_OK && !push_field(&r, field)) {
                free(field);
                st = CSV_ERR_MEMORY;
            }
            if (st != CSV_OK) {
                free_row(&r);
                free_rows(&rs);
                return st;
            }
            if (i >= len || s[i] != ',') {
                break;
            }
            i++;
        }
        i += line_break(s, len, i);
        if (!push_row(&rs, r)) {
            free_row(&r);
            free_rows(&rs);
            return CSV_ERR_MEMORY;
        }
    }
    *out = rs;
    return CSV_OK;
}

// Reads the whole file into a new buffer.
static enum csv_status read_file(const char *path, char **data, size_t *len) {
    FILE *f = fopen(path, "rb");
    if (f == nullptr) {
        return CSV_ERR_IO;
    }
    struct bytes b = {0};
    char chunk[4096];
    size_t got;
    while ((got = fread(chunk, 1, sizeof chunk, f)) > 0) {
        for (size_t k = 0; k < got; k++) {
            if (!push_byte(&b, chunk[k])) {
                free(b.p);
                fclose(f);
                return CSV_ERR_MEMORY;
            }
        }
    }
    bool failed = ferror(f);
    fclose(f);
    if (failed) {
        free(b.p);
        return CSV_ERR_IO;
    }
    *data = b.p; // null for an empty file
    *len = b.n;
    return CSV_OK;
}

enum csv_status read_csv(const char *path, struct csv_table *out) {
    *out = (struct csv_table){0};
    char *data = nullptr;
    size_t len = 0;
    enum csv_status st = read_file(path, &data, &len);
    if (st != CSV_OK) {
        return st;
    }
    const char *s = data;
    if (len >= 3 && memcmp(s, "\xEF\xBB\xBF", 3) == 0) { // the UTF-8 byte order mark
        s += 3;
        len -= 3;
    }
    struct rows rs = {0};
    st = parse_csv(s, len, &rs);
    free(data);
    if (st != CSV_OK) {
        return st;
    }
    if (rs.n == 0) {
        free(rs.p);
        return CSV_OK;
    }
    for (size_t r = 1; r < rs.n; r++) {
        if (rs.p[r].n != rs.p[0].n) {
            free_rows(&rs);
            return CSV_ERR_FIELD_COUNT;
        }
    }
    char ***records = rs.n > 1 ? malloc((rs.n - 1) * sizeof *records) : nullptr;
    if (rs.n > 1 && records == nullptr) {
        free_rows(&rs);
        return CSV_ERR_MEMORY;
    }
    for (size_t r = 1; r < rs.n; r++) {
        records[r - 1] = rs.p[r].fields;
    }
    *out = (struct csv_table){
        .ncols = rs.p[0].n, .header = rs.p[0].fields, .nrecords = rs.n - 1, .records = records};
    free(rs.p);
    return CSV_OK;
}

const char *csv_field(const struct csv_table *t, size_t r, const char *name) {
    for (size_t c = 0; c < t->ncols; c++) {
        if (strcmp(t->header[c], name) == 0) {
            return t->records[r][c];
        }
    }
    return nullptr;
}

void csv_table_free(struct csv_table *t) {
    for (size_t r = 0; r < t->nrecords; r++) {
        for (size_t c = 0; c < t->ncols; c++) {
            free(t->records[r][c]);
        }
        free(t->records[r]);
    }
    for (size_t c = 0; c < t->ncols; c++) {
        free(t->header[c]);
    }
    free(t->header);
    free(t->records);
    *t = (struct csv_table){0};
}
read_csv.h 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

#ifndef READ_CSV_H
#define READ_CSV_H

#include <stddef.h>

enum csv_status {
    CSV_OK = 0,
    CSV_ERR_IO,          // the file cannot be read; errno tells why
    CSV_ERR_FIELD_COUNT, // a record has more or fewer fields than the header
    CSV_ERR_BAD_QUOTE,   // a quoted field has no closing quote, or has text after it
    CSV_ERR_MEMORY,
};

// A CSV file with a header. records[r][c] is the field of record r in the column header[c].
struct csv_table {
    size_t ncols;
    char **header;
    size_t nrecords;
    char ***records;
};

// Reads the CSV file at path into *out. On an error, *out is empty and needs no free.
enum csv_status read_csv(const char *path, struct csv_table *out);

// Returns the field of record r in the column with the given name, or NULL if no column has that name.
const char *csv_field(const struct csv_table *t, size_t r, const char *name);

void csv_table_free(struct csv_table *t);

#endif
test_read_csv.c 138 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

#define _POSIX_C_SOURCE 200809L

#include "read_csv.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define MAX 4

// Each record is written as "name=field" pairs joined by "|".
struct test_case {
    const char *name;
    const char *data;
    const char *want[MAX];
};

static const struct test_case cases[] = {
    {"simple", "name,age\nAda,36\nAlan,41\n", {"name=Ada|age=36", "name=Alan|age=41"}},
    {"crlf", "name,age\r\nAda,36\r\nAlan,41\r\n", {"name=Ada|age=36", "name=Alan|age=41"}},
    {"no-final-newline", "name,age\nAda,36\nAlan,41", {"name=Ada|age=36", "name=Alan|age=41"}},
    {"quoted-comma", "name,born\n\"Lovelace, Ada\",1815\n", {"name=Lovelace, Ada|born=1815"}},
    {"escaped-quote", "id,quote\n1,\"She said \"\"hi\"\".\"\n", {"id=1|quote=She said \"hi\"."}},
    {"quoted-header", "\"first name\",\"last name\"\nAda,Lovelace\n", {"first name=Ada|last name=Lovelace"}},
    {"newline-in-field", "id,address\n1,\"12 High St\nLeeds\"\n", {"id=1|address=12 High St\nLeeds"}},
    {"crlf-in-field", "id,address\r\n1,\"12 High St\r\nLeeds\"\r\n", {"id=1|address=12 High St\nLeeds"}},
    {"blank-line-in-field", "id,note\n1,\"one\n\ntwo\"\n", {"id=1|note=one\n\ntwo"}},
    {"empty-last-line", "a,b\n1,2\n\n", {"a=1|b=2"}},
    {"blank-lines", "a,b\n\n1,2\n\n\n3,4\n", {"a=1|b=2", "a=3|b=4"}},
    {"empty-fields", "a,b,c\n,,\n", {"a=|b=|c="}},
    {"quoted-empty", "name\n\"\"\n", {"name="}},
    {"spaces", "a,b\n x , y \n", {"a= x |b= y "}},
    {"header-only", "a,b\n", {nullptr}},
    {"empty-file", "", {nullptr}},
    {"bom", "\xEF\xBB\xBFname,age\nAda,36\n", {"name=Ada|age=36"}},
    {"non-ascii", "city,country\nZürich,Schweiz\n東京,日本\n", {"city=Zürich|country=Schweiz", "city=東京|country=日本"}},
};

struct invalid_case {
    const char *name;
    const char *data;
    enum csv_status want;
};

static const struct invalid_case invalid[] = {
    {"too-few-fields", "a,b\n1\n", CSV_ERR_FIELD_COUNT},
    {"too-many-fields", "a,b\n1,2,3\n", CSV_ERR_FIELD_COUNT},
    {"unclosed-quote", "a,b\n1,\"two\n", CSV_ERR_BAD_QUOTE},
    {"text-after-quote", "a,b\n1,\"two\"x\n", CSV_ERR_BAD_QUOTE},
};

// Writes data to a new temporary file and stores its path in path.
static int write_temp(char path[static 32], const char *data) {
    strcpy(path, "/tmp/read-csv-XXXXXX");
    int fd = mkstemp(path);
    if (fd < 0) {
        perror("mkstemp");
        return -1;
    }
    size_t len = strlen(data);
    bool ok = write(fd, data, len) == (ssize_t)len;
    close(fd);
    return ok ? 0 : -1;
}

// Joins the fields of record r as "name=field|...".
static void join(const struct csv_table *t, size_t r, char *out, size_t size) {
    out[0] = '\0';
    for (size_t c = 0; c < t->ncols; c++) {
        size_t used = strlen(out);
        snprintf(out + used, size - used, "%s%s=%s", c ? "|" : "", t->header[c], t->records[r][c]);
    }
}

int main(void) {
    int failed = 0;
    char path[32];
    char got[256];
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *tc = &cases[i];
        if (write_temp(path, tc->data) != 0) {
            return 1;
        }
        struct csv_table t;
        enum csv_status st = read_csv(path, &t);
        unlink(path);
        size_t nwant = 0;
        while (nwant < MAX && tc->want[nwant] != nullptr) {
            nwant++;
        }
        bool ok = st == CSV_OK && t.nrecords == nwant;
        for (size_t r = 0; ok && r < nwant; r++) {
            join(&t, r, got, sizeof got);
            ok = strcmp(got, tc->want[r]) == 0;
        }
        if (!ok) {
            fprintf(stderr, "FAIL %s: status %d, %zu records\n", tc->name, (int)st, t.nrecords);
            failed++;
        }
        csv_table_free(&t);
    }
    for (size_t i = 0; i < sizeof invalid / sizeof invalid[0]; i++) {
        if (write_temp(path, invalid[i].data) != 0) {
            return 1;
        }
        struct csv_table t;
        enum csv_status st = read_csv(path, &t);
        unlink(path);
        if (st != invalid[i].want || t.nrecords != 0) {
            fprintf(stderr, "FAIL %s: status %d\n", invalid[i].name, (int)st);
            failed++;
        }
    }
    struct csv_table t;
    if (read_csv("/nonexistent/read-csv/missing.csv", &t) != CSV_ERR_IO) {
        fprintf(stderr, "FAIL missing\n");
        failed++;
    }
    if (write_temp(path, "name,age\nAda,36\n") != 0 || read_csv(path, &t) != CSV_OK) {
        return 1;
    }
    unlink(path);
    const char *age = csv_field(&t, 0, "age");
    if (age == nullptr || strcmp(age, "36") != 0 || csv_field(&t, 0, "town") != nullptr) {
        fprintf(stderr, "FAIL csv_field\n");
        failed++;
    }
    csv_table_free(&t);
    if (failed > 0) {
        return 1;
    }
    printf("ok\n");
    return 0;
}
ReadCsv.csI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

using System.Text;

/// <summary>The error for a file that is not valid CSV. Kind is "field-count" or "bad-quote".</summary>
public sealed class CsvException(string kind, string message) : FormatException(message)
{
    public string Kind { get; } = kind;
}

/// <summary>Reads a CSV file of RFC 4180 with a header line.</summary>
public static class ReadCsv
{
    /// <summary>Returns one dictionary for each record after the header, from each name to its field.</summary>
    /// <exception cref="CsvException">a bad quote, or a record with the wrong number of fields.</exception>
    public static List<Dictionary<string, string>> Read(string path)
    {
        // ReadAllText detects and removes a UTF-8 byte order mark.
        string text = File.ReadAllText(path, Encoding.UTF8);
        List<List<string>> rows = Parse(text);
        var records = new List<Dictionary<string, string>>();
        if (rows.Count == 0)
        {
            return records;
        }
        List<string> header = rows[0];
        for (int n = 1; n < rows.Count; n++)
        {
            List<string> row = rows[n];
            if (row.Count != header.Count)
            {
                throw new CsvException("field-count", $"record {n} has {row.Count} fields, want {header.Count}");
            }
            var record = new Dictionary<string, string>(header.Count);
            for (int k = 0; k < row.Count; k++)
            {
                record.Add(header[k], row[k]);
            }
            records.Add(record);
        }
        return records;
    }

    /// <summary>Returns the length of the line break at i: 1 for LF, 2 for CRLF, 0 for none.</summary>
    private static int LineBreak(string text, int i)
    {
        if (i < text.Length && text[i] == '\n')
        {
            return 1;
        }
        return i + 1 < text.Length && text[i] == '\r' && text[i + 1] == '\n' ? 2 : 0;
    }

    /// <summary>Splits RFC 4180 text into records of fields. An empty line gives no record.</summary>
    public static List<List<string>> Parse(string text)
    {
        var records = new List<List<string>>();
        int i = 0;
        while (i < text.Length)
        {
            int empty = LineBreak(text, i);
            if (empty > 0)
            {
                i += empty;
                continue;
            }
            var record = new List<string>();
            while (true)
            {
                var field = new StringBuilder();
                if (i < text.Length && text[i] == '"')
                {
                    i++;
                    while (true)
                    {
                        if (i >= text.Length)
                        {
                            throw new CsvException("bad-quote", "a quoted field has no closing quote");
                        }
                        if (text[i] == '"')
                        {
                            if (i + 1 >= text.Length || text[i + 1] != '"')
                            {
                                break;
                            }
                            field.Append('"');
                            i += 2;
                        }
                        else if (LineBreak(text, i) == 2)
                        {
                            field.Append('\n'); // CRLF inside quotes becomes LF.
                            i += 2;
                        }
                        else
                        {
                            field.Append(text[i++]);
                        }
                    }
                    i++; // the closing quote
                    if (i < text.Length && text[i] != ',' && LineBreak(text, i) == 0)
                    {
                        throw new CsvException("bad-quote", "text after the closing quote of a field");
                    }
                }
                else
                {
                    while (i < text.Length && text[i] != ',' && LineBreak(text, i) == 0)
                    {
                        field.Append(text[i++]);
                    }
                }
                record.Add(field.ToString());
                if (i >= text.Length || text[i] != ',')
                {
                    break;
                }
                i++;
            }
            i += LineBreak(text, i);
            records.Add(record);
        }
        return records;
    }
}
ReadCsvTests.cs 67 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

using System.Text;
using Xunit;

public sealed class ReadCsvTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("read-csv-").FullName;

    public void Dispose() => Directory.Delete(dir, recursive: true);

    private string Write(string text)
    {
        string path = Path.Combine(dir, "input.csv");
        File.WriteAllBytes(path, Encoding.UTF8.GetBytes(text));
        return path;
    }

    // Each record is written as "name=field" pairs joined by "|", so that TheoryData can hold it.
    public static TheoryData<string, string, string[]> Cases => new()
    {
        { "simple", "name,age\nAda,36\nAlan,41\n", ["name=Ada|age=36", "name=Alan|age=41"] },
        { "crlf", "name,age\r\nAda,36\r\nAlan,41\r\n", ["name=Ada|age=36", "name=Alan|age=41"] },
        { "no-final-newline", "name,age\nAda,36\nAlan,41", ["name=Ada|age=36", "name=Alan|age=41"] },
        { "quoted-comma", "name,born\n\"Lovelace, Ada\",1815\n", ["name=Lovelace, Ada|born=1815"] },
        { "escaped-quote", "id,quote\n1,\"She said \"\"hi\"\".\"\n", ["id=1|quote=She said \"hi\"."] },
        { "quoted-header", "\"first name\",\"last name\"\nAda,Lovelace\n", ["first name=Ada|last name=Lovelace"] },
        { "newline-in-field", "id,address\n1,\"12 High St\nLeeds\"\n", ["id=1|address=12 High St\nLeeds"] },
        { "crlf-in-field", "id,address\r\n1,\"12 High St\r\nLeeds\"\r\n", ["id=1|address=12 High St\nLeeds"] },
        { "blank-line-in-field", "id,note\n1,\"one\n\ntwo\"\n", ["id=1|note=one\n\ntwo"] },
        { "empty-last-line", "a,b\n1,2\n\n", ["a=1|b=2"] },
        { "blank-lines", "a,b\n\n1,2\n\n\n3,4\n", ["a=1|b=2", "a=3|b=4"] },
        { "empty-fields", "a,b,c\n,,\n", ["a=|b=|c="] },
        { "quoted-empty", "name\n\"\"\n", ["name="] },
        { "spaces", "a,b\n x , y \n", ["a= x |b= y "] },
        { "header-only", "a,b\n", [] },
        { "empty-file", "", [] },
        { "bom", "\uFEFFname,age\nAda,36\n", ["name=Ada|age=36"] },
        { "non-ascii", "city,country\nZürich,Schweiz\n東京,日本\n", ["city=Zürich|country=Schweiz", "city=東京|country=日本"] },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Reads(string name, string text, string[] want)
    {
        Assert.False(string.IsNullOrEmpty(name));
        var got = ReadCsv.Read(Write(text)).Select(r => string.Join("|", r.Select(kv => $"{kv.Key}={kv.Value}")));
        Assert.Equal(want, got);
    }

    [Theory]
    [InlineData("too-few-fields", "a,b\n1\n", "field-count")]
    [InlineData("too-many-fields", "a,b\n1,2,3\n", "field-count")]
    [InlineData("unclosed-quote", "a,b\n1,\"two\n", "bad-quote")]
    [InlineData("text-after-quote", "a,b\n1,\"two\"x\n", "bad-quote")]
    public void Invalid(string name, string text, string kind)
    {
        Assert.False(string.IsNullOrEmpty(name));
        string path = Write(text);
        Assert.Equal(kind, Assert.Throws<CsvException>(() => ReadCsv.Read(path)).Kind);
    }

    [Fact]
    public void Missing() =>
        Assert.Throws<FileNotFoundException>(() => ReadCsv.Read(Path.Combine(dir, "missing.csv")));
}
readCsv.jsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

import { readFile } from "node:fs/promises";

/** The error for a file that is not valid CSV. kind is "field-count" or "bad-quote". */
export class CsvError extends Error {
  /**
   * @param {"field-count" | "bad-quote"} kind
   * @param {string} message
   */
  constructor(kind, message) {
    super(message);
    this.name = "CsvError";
    this.kind = kind;
  }
}

/** Returns the length of the line break at i: 1 for LF, 2 for CRLF, 0 for none. */
function lineBreak(text, i) {
  if (text[i] === "\n") return 1;
  if (text[i] === "\r" && text[i + 1] === "\n") return 2;
  return 0;
}

/**
 * Splits RFC 4180 text into records of fields. An empty line gives no record.
 * @param {string} text
 * @returns {string[][]}
 */
export function parseCsv(text) {
  const records = [];
  let i = 0;
  while (i < text.length) {
    const empty = lineBreak(text, i);
    if (empty > 0) {
      i += empty;
      continue;
    }
    const record = [];
    for (;;) {
      let field = "";
      if (text[i] === '"') {
        i++;
        for (;;) {
          if (i >= text.length) throw new CsvError("bad-quote", "a quoted field has no closing quote");
          if (text[i] === '"') {
            if (text[i + 1] !== '"') break;
            field += '"';
            i += 2;
          } else if (lineBreak(text, i) === 2) {
            field += "\n"; // CRLF inside quotes becomes LF.
            i += 2;
          } else {
            field += text[i++];
          }
        }
        i++; // the closing quote
        if (i < text.length && text[i] !== "," && lineBreak(text, i) === 0) {
          throw new CsvError("bad-quote", "text after the closing quote of a field");
        }
      } else {
        const start = i;
        while (i < text.length && text[i] !== "," && lineBreak(text, i) === 0) i++;
        field = text.slice(start, i);
      }
      record.push(field);
      if (text[i] !== ",") break;
      i++;
    }
    i += lineBreak(text, i);
    records.push(record);
  }
  return records;
}

/**
 * Reads a CSV file with a header line into one object for each record.
 * @param {string} path
 * @returns {Promise<Record<string, string>[]>}
 */
export async function readCsv(path) {
  let text = await readFile(path, "utf8");
  if (text.startsWith("\uFEFF")) text = text.slice(1);
  const [header, ...rows] = parseCsv(text);
  if (header === undefined) return [];
  return rows.map((row, n) => {
    if (row.length !== header.length) {
      throw new CsvError("field-count", `record ${n + 1} has ${row.length} fields, want ${header.length}`);
    }
    // fromEntries makes own properties, also for a name such as "__proto__".
    return Object.fromEntries(header.map((name, k) => [name, row[k]]));
  });
}
readCsv.test.js 73 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";

import { CsvError, readCsv } from "./readCsv.js";

const ADA_ALAN = [
  { name: "Ada", age: "36" },
  { name: "Alan", age: "41" },
];

const CASES = {
  simple: ["name,age\nAda,36\nAlan,41\n", ADA_ALAN],
  crlf: ["name,age\r\nAda,36\r\nAlan,41\r\n", ADA_ALAN],
  "no-final-newline": ["name,age\nAda,36\nAlan,41", ADA_ALAN],
  "quoted-comma": ['name,born\n"Lovelace, Ada",1815\n', [{ name: "Lovelace, Ada", born: "1815" }]],
  "escaped-quote": ['id,quote\n1,"She said ""hi""."\n', [{ id: "1", quote: 'She said "hi".' }]],
  "quoted-header": ['"first name","last name"\nAda,Lovelace\n', [{ "first name": "Ada", "last name": "Lovelace" }]],
  "newline-in-field": ['id,address\n1,"12 High St\nLeeds"\n', [{ id: "1", address: "12 High St\nLeeds" }]],
  "crlf-in-field": ['id,address\r\n1,"12 High St\r\nLeeds"\r\n', [{ id: "1", address: "12 High St\nLeeds" }]],
  "blank-line-in-field": ['id,note\n1,"one\n\ntwo"\n', [{ id: "1", note: "one\n\ntwo" }]],
  "empty-last-line": ["a,b\n1,2\n\n", [{ a: "1", b: "2" }]],
  "blank-lines": ["a,b\n\n1,2\n\n\n3,4\n", [{ a: "1", b: "2" }, { a: "3", b: "4" }]],
  "empty-fields": ["a,b,c\n,,\n", [{ a: "", b: "", c: "" }]],
  "quoted-empty": ['name\n""\n', [{ name: "" }]],
  spaces: ["a,b\n x , y \n", [{ a: " x ", b: " y " }]],
  "header-only": ["a,b\n", []],
  "empty-file": ["", []],
  bom: ["\uFEFFname,age\nAda,36\n", [{ name: "Ada", age: "36" }]],
  "non-ascii": ["city,country\nZürich,Schweiz\n東京,日本\n", [{ city: "Zürich", country: "Schweiz" }, { city: "東京", country: "日本" }]],
};

const INVALID = {
  "too-few-fields": ["a,b\n1\n", "field-count"],
  "too-many-fields": ["a,b\n1,2,3\n", "field-count"],
  "unclosed-quote": ['a,b\n1,"two\n', "bad-quote"],
  "text-after-quote": ['a,b\n1,"two"x\n', "bad-quote"],
};

const dir = mkdtempSync(join(tmpdir(), "read-csv-"));
after(() => rmSync(dir, { recursive: true, force: true }));

function write(name, text) {
  const path = join(dir, `${name}.csv`);
  writeFileSync(path, text, "utf8");
  return path;
}

for (const [name, [text, want]] of Object.entries(CASES)) {
  test(name, async () => {
    assert.deepEqual(await readCsv(write(name, text)), want);
  });
}

for (const [name, [text, kind]] of Object.entries(INVALID)) {
  test(name, async () => {
    await assert.rejects(readCsv(write(name, text)), (e) => e instanceof CsvError && e.kind === kind);
  });
}

test("missing", async () => {
  await assert.rejects(readCsv(join(dir, "missing.csv")), { code: "ENOENT" });
});

test("proto header", async () => {
  const [record] = await readCsv(write("proto", "__proto__\nx\n"));
  assert.equal(Object.getOwnPropertyDescriptor(record, "__proto__")?.value, "x");
});
readCsv.tsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

import { readFile } from "node:fs/promises";

/** The error for a file that is not valid CSV. */
export class CsvError extends Error {
  readonly kind: "field-count" | "bad-quote";

  constructor(kind: "field-count" | "bad-quote", message: string) {
    super(message);
    this.name = "CsvError";
    this.kind = kind;
  }
}

/** Returns the length of the line break at i: 1 for LF, 2 for CRLF, 0 for none. */
function lineBreak(text: string, i: number): number {
  if (text[i] === "\n") return 1;
  if (text[i] === "\r" && text[i + 1] === "\n") return 2;
  return 0;
}

/** Splits RFC 4180 text into records of fields. An empty line gives no record. */
export function parseCsv(text: string): string[][] {
  const records: string[][] = [];
  let i = 0;
  while (i < text.length) {
    const empty = lineBreak(text, i);
    if (empty > 0) {
      i += empty;
      continue;
    }
    const record: string[] = [];
    for (;;) {
      let field = "";
      if (text[i] === '"') {
        i++;
        for (;;) {
          if (i >= text.length) throw new CsvError("bad-quote", "a quoted field has no closing quote");
          if (text[i] === '"') {
            if (text[i + 1] !== '"') break;
            field += '"';
            i += 2;
          } else if (lineBreak(text, i) === 2) {
            field += "\n"; // CRLF inside quotes becomes LF.
            i += 2;
          } else {
            field += text[i++];
          }
        }
        i++; // the closing quote
        if (i < text.length && text[i] !== "," && lineBreak(text, i) === 0) {
          throw new CsvError("bad-quote", "text after the closing quote of a field");
        }
      } else {
        const start = i;
        while (i < text.length && text[i] !== "," && lineBreak(text, i) === 0) i++;
        field = text.slice(start, i);
      }
      record.push(field);
      if (text[i] !== ",") break;
      i++;
    }
    i += lineBreak(text, i);
    records.push(record);
  }
  return records;
}

/** Reads a CSV file with a header line into one object for each record. */
export async function readCsv(path: string): Promise<Record<string, string>[]> {
  let text = await readFile(path, "utf8");
  if (text.startsWith("\uFEFF")) text = text.slice(1);
  const [header, ...rows] = parseCsv(text);
  if (header === undefined) return [];
  return rows.map((row, n) => {
    if (row.length !== header.length) {
      throw new CsvError("field-count", `record ${n + 1} has ${row.length} fields, want ${header.length}`);
    }
    // fromEntries makes own properties, also for a name such as "__proto__".
    return Object.fromEntries(header.map((name, k) => [name, row[k] ?? ""]));
  });
}
readCsv.test.ts 73 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";

import { CsvError, readCsv } from "./readCsv.ts";

const ADA_ALAN = [
  { name: "Ada", age: "36" },
  { name: "Alan", age: "41" },
];

const CASES: Record<string, [string, Record<string, string>[]]> = {
  simple: ["name,age\nAda,36\nAlan,41\n", ADA_ALAN],
  crlf: ["name,age\r\nAda,36\r\nAlan,41\r\n", ADA_ALAN],
  "no-final-newline": ["name,age\nAda,36\nAlan,41", ADA_ALAN],
  "quoted-comma": ['name,born\n"Lovelace, Ada",1815\n', [{ name: "Lovelace, Ada", born: "1815" }]],
  "escaped-quote": ['id,quote\n1,"She said ""hi""."\n', [{ id: "1", quote: 'She said "hi".' }]],
  "quoted-header": ['"first name","last name"\nAda,Lovelace\n', [{ "first name": "Ada", "last name": "Lovelace" }]],
  "newline-in-field": ['id,address\n1,"12 High St\nLeeds"\n', [{ id: "1", address: "12 High St\nLeeds" }]],
  "crlf-in-field": ['id,address\r\n1,"12 High St\r\nLeeds"\r\n', [{ id: "1", address: "12 High St\nLeeds" }]],
  "blank-line-in-field": ['id,note\n1,"one\n\ntwo"\n', [{ id: "1", note: "one\n\ntwo" }]],
  "empty-last-line": ["a,b\n1,2\n\n", [{ a: "1", b: "2" }]],
  "blank-lines": ["a,b\n\n1,2\n\n\n3,4\n", [{ a: "1", b: "2" }, { a: "3", b: "4" }]],
  "empty-fields": ["a,b,c\n,,\n", [{ a: "", b: "", c: "" }]],
  "quoted-empty": ['name\n""\n', [{ name: "" }]],
  spaces: ["a,b\n x , y \n", [{ a: " x ", b: " y " }]],
  "header-only": ["a,b\n", []],
  "empty-file": ["", []],
  bom: ["\uFEFFname,age\nAda,36\n", [{ name: "Ada", age: "36" }]],
  "non-ascii": ["city,country\nZürich,Schweiz\n東京,日本\n", [{ city: "Zürich", country: "Schweiz" }, { city: "東京", country: "日本" }]],
};

const INVALID: Record<string, [string, string]> = {
  "too-few-fields": ["a,b\n1\n", "field-count"],
  "too-many-fields": ["a,b\n1,2,3\n", "field-count"],
  "unclosed-quote": ['a,b\n1,"two\n', "bad-quote"],
  "text-after-quote": ['a,b\n1,"two"x\n', "bad-quote"],
};

const dir = mkdtempSync(join(tmpdir(), "read-csv-"));
after(() => rmSync(dir, { recursive: true, force: true }));

function write(name: string, text: string): string {
  const path = join(dir, `${name}.csv`);
  writeFileSync(path, text, "utf8");
  return path;
}

for (const [name, [text, want]] of Object.entries(CASES)) {
  test(name, async () => {
    assert.deepEqual(await readCsv(write(name, text)), want);
  });
}

for (const [name, [text, kind]] of Object.entries(INVALID)) {
  test(name, async () => {
    await assert.rejects(readCsv(write(name, text)), (e: unknown) => e instanceof CsvError && e.kind === kind);
  });
}

test("missing", async () => {
  await assert.rejects(readCsv(join(dir, "missing.csv")), { code: "ENOENT" });
});

test("proto header", async () => {
  const [record] = await readCsv(write("proto", "__proto__\nx\n"));
  assert.equal(Object.getOwnPropertyDescriptor(record, "__proto__")?.value, "x");
});
read_csv.goI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

// Package readcsv reads a CSV file of RFC 4180 with a header line.
package readcsv

import (
	"bufio"
	"bytes"
	"encoding/csv"
	"errors"
	"io"
	"os"
)

// ReadCSV returns one map for each record after the header, from each name to
// its field. A bad quote gives a *csv.ParseError that wraps csv.ErrQuote, and a
// record with the wrong number of fields one that wraps csv.ErrFieldCount.
func ReadCSV(path string) ([]map[string]string, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	in := bufio.NewReader(f)
	// encoding/csv does not remove a byte order mark.
	if b, err := in.Peek(3); err == nil && bytes.Equal(b, []byte("\xEF\xBB\xBF")) {
		in.Discard(3)
	}
	r := csv.NewReader(in)
	// FieldsPerRecord 0, the default, takes the count from the first record.
	r.FieldsPerRecord = 0
	header, err := r.Read()
	if errors.Is(err, io.EOF) {
		return []map[string]string{}, nil
	}
	if err != nil {
		return nil, err
	}
	records := []map[string]string{}
	for {
		row, err := r.Read()
		if errors.Is(err, io.EOF) {
			return records, nil
		}
		if err != nil {
			return nil, err
		}
		record := make(map[string]string, len(header))
		for i, name := range header {
			record[name] = row[i]
		}
		records = append(records, record)
	}
}
read_csv_test.go 85 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

package readcsv

import (
	"encoding/csv"
	"errors"
	"io/fs"
	"os"
	"path/filepath"
	"reflect"
	"testing"
)

type rec = map[string]string

func write(t *testing.T, data string) string {
	t.Helper()
	path := filepath.Join(t.TempDir(), "input.csv")
	if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
		t.Fatal(err)
	}
	return path
}

func TestCases(t *testing.T) {
	adaAlan := []rec{{"name": "Ada", "age": "36"}, {"name": "Alan", "age": "41"}}
	cases := []struct {
		name, data string
		want       []rec
	}{
		{"simple", "name,age\nAda,36\nAlan,41\n", adaAlan},
		{"crlf", "name,age\r\nAda,36\r\nAlan,41\r\n", adaAlan},
		{"no-final-newline", "name,age\nAda,36\nAlan,41", adaAlan},
		{"quoted-comma", "name,born\n\"Lovelace, Ada\",1815\n", []rec{{"name": "Lovelace, Ada", "born": "1815"}}},
		{"escaped-quote", "id,quote\n1,\"She said \"\"hi\"\".\"\n", []rec{{"id": "1", "quote": `She said "hi".`}}},
		{"quoted-header", "\"first name\",\"last name\"\nAda,Lovelace\n", []rec{{"first name": "Ada", "last name": "Lovelace"}}},
		{"newline-in-field", "id,address\n1,\"12 High St\nLeeds\"\n", []rec{{"id": "1", "address": "12 High St\nLeeds"}}},
		{"crlf-in-field", "id,address\r\n1,\"12 High St\r\nLeeds\"\r\n", []rec{{"id": "1", "address": "12 High St\nLeeds"}}},
		{"blank-line-in-field", "id,note\n1,\"one\n\ntwo\"\n", []rec{{"id": "1", "note": "one\n\ntwo"}}},
		{"empty-last-line", "a,b\n1,2\n\n", []rec{{"a": "1", "b": "2"}}},
		{"blank-lines", "a,b\n\n1,2\n\n\n3,4\n", []rec{{"a": "1", "b": "2"}, {"a": "3", "b": "4"}}},
		{"empty-fields", "a,b,c\n,,\n", []rec{{"a": "", "b": "", "c": ""}}},
		{"quoted-empty", "name\n\"\"\n", []rec{{"name": ""}}},
		{"spaces", "a,b\n x , y \n", []rec{{"a": " x ", "b": " y "}}},
		{"header-only", "a,b\n", []rec{}},
		{"empty-file", "", []rec{}},
		{"bom", "\uFEFFname,age\nAda,36\n", []rec{{"name": "Ada", "age": "36"}}},
		{"non-ascii", "city,country\nZürich,Schweiz\n東京,日本\n", []rec{{"city": "Zürich", "country": "Schweiz"}, {"city": "東京", "country": "日本"}}},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got, err := ReadCSV(write(t, c.data))
			if err != nil || !reflect.DeepEqual(got, c.want) {
				t.Errorf("ReadCSV = %q, %v; want %q, nil", got, err, c.want)
			}
		})
	}
}

func TestInvalid(t *testing.T) {
	cases := []struct {
		name, data string
		want       error
	}{
		{"too-few-fields", "a,b\n1\n", csv.ErrFieldCount},
		{"too-many-fields", "a,b\n1,2,3\n", csv.ErrFieldCount},
		{"unclosed-quote", "a,b\n1,\"two\n", csv.ErrQuote},
		{"text-after-quote", "a,b\n1,\"two\"x\n", csv.ErrQuote},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if _, err := ReadCSV(write(t, c.data)); !errors.Is(err, c.want) {
				t.Errorf("err = %v, want %v", err, c.want)
			}
		})
	}
}

func TestMissing(t *testing.T) {
	if _, err := ReadCSV(filepath.Join(t.TempDir(), "missing.csv")); !errors.Is(err, fs.ErrNotExist) {
		t.Errorf("err = %v, want fs.ErrNotExist", err)
	}
}
read_csv.rsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

//! Reads a CSV file of RFC 4180 with a header line. The standard library has no CSV reader, so this file has a small parser.

use std::collections::HashMap;
use std::fmt;
use std::fs;
use std::io;
use std::path::Path;

/// The error for a file that cannot be read or is not valid CSV.
#[derive(Debug)]
pub enum CsvError {
    /// The file cannot be opened or is not UTF-8.
    Io(io::Error),
    /// A record has more or fewer fields than the header.
    FieldCount { record: usize, got: usize, want: usize },
    /// A quoted field has no closing quote, or has text after it.
    BadQuote(&'static str),
}

impl fmt::Display for CsvError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CsvError::Io(err) => write!(f, "{err}"),
            CsvError::FieldCount { record, got, want } => {
                write!(f, "record {record} has {got} fields, want {want}")
            }
            CsvError::BadQuote(why) => write!(f, "{why}"),
        }
    }
}

impl std::error::Error for CsvError {}

impl From<io::Error> for CsvError {
    fn from(err: io::Error) -> Self {
        CsvError::Io(err)
    }
}

/// Returns the length of the line break at i: 1 for LF, 2 for CRLF, 0 for none.
fn line_break(b: &[u8], i: usize) -> usize {
    match (b.get(i), b.get(i + 1)) {
        (Some(b'\n'), _) => 1,
        (Some(b'\r'), Some(b'\n')) => 2,
        _ => 0,
    }
}

/// Splits RFC 4180 text into records of fields. An empty line gives no record.
pub fn parse_csv(text: &str) -> Result<Vec<Vec<String>>, CsvError> {
    // The parser splits only at ASCII bytes, so each field stays valid UTF-8.
    let b = text.as_bytes();
    let mut records = Vec::new();
    let mut i = 0;
    while i < b.len() {
        let empty = line_break(b, i);
        if empty > 0 {
            i += empty;
            continue;
        }
        let mut record = Vec::new();
        loop {
            let mut field = Vec::new();
            if b.get(i) == Some(&b'"') {
                i += 1;
                loop {
                    match b.get(i) {
                        None => return Err(CsvError::BadQuote("a quoted field has no closing quote")),
                        Some(b'"') if b.get(i + 1) == Some(&b'"') => {
                            field.push(b'"');
                            i += 2;
                        }
                        Some(b'"') => break,
                        Some(_) if line_break(b, i) == 2 => {
                            field.push(b'\n'); // CRLF inside quotes becomes LF.
                            i += 2;
                        }
                        Some(&c) => {
                            field.push(c);
                            i += 1;
                        }
                    }
                }
                i += 1; // the closing quote
                if i < b.len() && b[i] != b',' && line_break(b, i) == 0 {
                    return Err(CsvError::BadQuote("text after the closing quote of a field"));
                }
            } else {
                while i < b.len() && b[i] != b',' && line_break(b, i) == 0 {
                    field.push(b[i]);
                    i += 1;
                }
            }
            record.push(String::from_utf8(field).expect("a field ends at an ASCII byte"));
            if b.get(i) != Some(&b',') {
                break;
            }
            i += 1;
        }
        i += line_break(b, i);
        records.push(record);
    }
    Ok(records)
}

/// Returns one map for each record after the header, from each name to its field.
pub fn read_csv(path: impl AsRef<Path>) -> Result<Vec<HashMap<String, String>>, CsvError> {
    // read_to_string fails with InvalidData if the file is not UTF-8.
    let text = fs::read_to_string(path)?;
    let text = text.strip_prefix('\u{FEFF}').unwrap_or(&text);
    let mut rows = parse_csv(text)?.into_iter();
    let Some(header) = rows.next() else {
        return Ok(Vec::new());
    };
    rows.enumerate()
        .map(|(n, row)| {
            if row.len() != header.len() {
                return Err(CsvError::FieldCount { record: n + 1, got: row.len(), want: header.len() });
            }
            Ok(header.iter().cloned().zip(row).collect())
        })
        .collect()
}
tests/read_csv_test.rs 93 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-csv-file/.

use std::collections::HashMap;
use std::fs;
use std::io::ErrorKind;
use std::path::PathBuf;

use algo_read_a_csv_file::{CsvError, read_csv};

/// A file in the temporary directory that is removed when the value is dropped.
struct Input(PathBuf);

impl Input {
    fn new(name: &str, data: &str) -> Input {
        let path = std::env::temp_dir().join(format!("read-csv-{}-{name}.csv", std::process::id()));
        fs::write(&path, data).unwrap();
        Input(path)
    }
}

impl Drop for Input {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.0);
    }
}

fn recs(rows: &[&[(&str, &str)]]) -> Vec<HashMap<String, String>> {
    rows.iter()
        .map(|row| row.iter().map(|&(k, v)| (k.to_string(), v.to_string())).collect())
        .collect()
}

#[test]
fn cases() {
    let ada_alan: &[&[(&str, &str)]] = &[&[("name", "Ada"), ("age", "36")], &[("name", "Alan"), ("age", "41")]];
    let cases: &[(&str, &str, &[&[(&str, &str)]])] = &[
        ("simple", "name,age\nAda,36\nAlan,41\n", ada_alan),
        ("crlf", "name,age\r\nAda,36\r\nAlan,41\r\n", ada_alan),
        ("no-final-newline", "name,age\nAda,36\nAlan,41", ada_alan),
        ("quoted-comma", "name,born\n\"Lovelace, Ada\",1815\n", &[&[("name", "Lovelace, Ada"), ("born", "1815")]]),
        ("escaped-quote", "id,quote\n1,\"She said \"\"hi\"\".\"\n", &[&[("id", "1"), ("quote", "She said \"hi\".")]]),
        ("quoted-header", "\"first name\",\"last name\"\nAda,Lovelace\n", &[&[("first name", "Ada"), ("last name", "Lovelace")]]),
        ("newline-in-field", "id,address\n1,\"12 High St\nLeeds\"\n", &[&[("id", "1"), ("address", "12 High St\nLeeds")]]),
        ("crlf-in-field", "id,address\r\n1,\"12 High St\r\nLeeds\"\r\n", &[&[("id", "1"), ("address", "12 High St\nLeeds")]]),
        ("blank-line-in-field", "id,note\n1,\"one\n\ntwo\"\n", &[&[("id", "1"), ("note", "one\n\ntwo")]]),
        ("empty-last-line", "a,b\n1,2\n\n", &[&[("a", "1"), ("b", "2")]]),
        ("blank-lines", "a,b\n\n1,2\n\n\n3,4\n", &[&[("a", "1"), ("b", "2")], &[("a", "3"), ("b", "4")]]),
        ("empty-fields", "a,b,c\n,,\n", &[&[("a", ""), ("b", ""), ("c", "")]]),
        ("quoted-empty", "name\n\"\"\n", &[&[("name", "")]]),
        ("spaces", "a,b\n x , y \n", &[&[("a", " x "), ("b", " y ")]]),
        ("header-only", "a,b\n", &[]),
        ("empty-file", "", &[]),
        ("bom", "\u{FEFF}name,age\nAda,36\n", &[&[("name", "Ada"), ("age", "36")]]),
        (
            "non-ascii",
            "city,country\nZürich,Schweiz\n東京,日本\n",
            &[&[("city", "Zürich"), ("country", "Schweiz")], &[("city", "東京"), ("country", "日本")]],
        ),
    ];
    for &(name, data, want) in cases {
        let input = Input::new(name, data);
        assert_eq!(read_csv(&input.0).unwrap(), recs(want), "{name}");
    }
}

#[test]
fn invalid() {
    let cases = [
        ("too-few-fields", "a,b\n1\n", "field-count"),
        ("too-many-fields", "a,b\n1,2,3\n", "field-count"),
        ("unclosed-quote", "a,b\n1,\"two\n", "bad-quote"),
        ("text-after-quote", "a,b\n1,\"two\"x\n", "bad-quote"),
    ];
    for (name, data, kind) in cases {
        let input = Input::new(name, data);
        let got = match read_csv(&input.0) {
            Err(CsvError::FieldCount { .. }) => "field-count",
            Err(CsvError::BadQuote(_)) => "bad-quote",
            other => panic!("{name}: {other:?}"),
        };
        assert_eq!(got, kind, "{name}");
    }
}

#[test]
fn missing() {
    let path = std::env::temp_dir().join(format!("read-csv-{}-missing.csv", std::process::id()));
    match read_csv(path) {
        Err(CsvError::Io(err)) => assert_eq!(err.kind(), ErrorKind::NotFound),
        other => panic!("{other:?}"),
    }
}

References

  1. Y. Shafranovich, RFC 4180: Common Format and MIME Type for Comma-Separated Values (CSV) Files, October 2005, 2 Definition of the CSV Format, rules 1 to 7 and the ABNF grammar
  2. The Python Standard Library, csv, csv.reader; csv.field_size_limit; csv.DictReader (restkey, restval); Dialect.strict; csv.Error; footnote 1
  3. The Python Standard Library, codecs, Encodings and Unicode, utf-8-sig
  4. Go standard library, package encoding/csv, Overview; Variables (ErrQuote, ErrFieldCount); type Reader (FieldsPerRecord, LazyQuotes)
  5. ECMA-262, ECMAScript 2026 Language Specification, 20.1.2.7 Object.fromEntries
  6. Java SE 25 API, java.nio.file.Files, readString(Path)
  7. .NET API reference, File.ReadAllText, ReadAllText(String, Encoding), Remarks
  8. .NET API reference, TextFieldParser.ReadFields, Remarks
  9. The Rust Standard Library, std::fs::read_to_string, Errors
  10. cppreference.com, fopen, the file access mode flag "b"

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (c)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (cpp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (csharp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (go)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (java)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (javascript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (python)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (rust)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (typescript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source

The native tests pass in 9 of 9 languages in this build.