Taskcore
Write a CSV file
Also called write comma-separated values, export records to CSV, save records as a CSV file, write a CSV file with a header.
Write a header and records to a CSV file as RFC 4180 defines it, with quotes around each field that holds a comma, a double quote or a line break, and CRLF after each record.
- Evidence
- Code in 9 languages
Task
Write a list of records to a CSV file. The first record is the header. Each record is a list of fields, and each field is a string.
The format is the one that RFC 4180 (section 2) defines:
-
"Each record is located on a separate line, delimited by a line break (CRLF)."1 Commas separate the fields.
-
"Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes."1 "If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote."1 For example, the field
She said "hi".is written as"She said ""hi"".". -
"Spaces are considered part of a field and should not be ignored."1 The solution writes them as they are.
-
Each record "should contain the same number of fields throughout the file."1
RFC 4180 says that "The last record in the file may or may not have an ending line break."1 The solution writes CRLF after each record, also after the last one. Then a program can add more records to the end of the file.
The solution quotes a field that holds a comma, a double quote, a CR or an LF. It does not quote other fields. A record with one empty field is a special case: without quotes, its line is empty, and a reader such as the one of Read a CSV file skips an empty line. So the solution writes that field as "".
The solution writes the file as UTF-8 with no byte order mark. No records give an empty file. A record with more or fewer fields than the header is an error (field-count), and the solution writes no file.
The entry point format_csv returns the text of the file, and the cases check that text. A second function writes the text to a path.
Solutions
The standard libraries of Python and Go have a CSV writer. The Python solution uses it. The Go solution does not, because the Go writer changes some fields (see the pitfalls). JavaScript, TypeScript, Java, C#, Rust, C and C++ have no CSV writer, so their solutions hold a small writer. The writer is the same in each language:
- Check that each record has the same number of fields as the header. If one does not, report
field-countbefore you write a byte. - For each field, if it holds
,,", CR or LF, or if it is the only field of its record and it is empty, write", then the field with each"written twice, then". Otherwise write the field as it is. - Write
,between the fields and CRLF after each record.
- Python.
csv.writerwith the default dialectexcelwrites the records. Thelineterminatorof the writer "defaults to '\r\n'".2 The default quoting isQUOTE_MINIMAL, which "Instructs writer objects to only quote those fields which contain special characters such as delimiter, quotechar, '\r', '\n' or any of the characters in lineterminator."2 The file is opened withencoding='utf-8'andnewline=''. The code checks the number of fields itself, because the writer does not, and raisesCsvError, a subclass ofValueError.format_csvwrites to anio.StringIOwithnewline=''. - JavaScript and TypeScript (Node.js).
formatCsvis the small writer.writeFileSyncwrites the text, and the default of itsencodingoption is'utf8'.3 The error is aCsvErrorwith akindfield. The TypeScript file adds types only. - Java.
formatCsvis the small writer, andFiles.writeStringwrites the text. "Characters are encoded into bytes using the UTF-8 charset."4CsvExceptionextendsIllegalArgumentExceptionand has akind(). - C#.
WriteCsv.Formatis the small writer, andFile.WriteAllTextwrites the text. "This method uses UTF-8 encoding without a Byte-Order Mark (BOM)".5CsvExceptionextendsFormatException. - Go.
FormatCSVis the small writer, with astrings.Builder.os.WriteFilewrites the bytes. A wrong number of fields gives a*FieldCountErrorwith the record number and the two counts. - Rust.
format_csvis the small writer. It takes&[Vec<S>]withS: AsRef<str>, so it accepts bothStringand&strfields.fs::writewrites the text. "This function will create a file if it does not exist, and will entirely replace its contents if it does."6CsvErroris an enum withIoandFieldCount. - C.
format_csvmeasures the text in a first pass, allocates it once, and fills it in a second pass.write_csvopens the file in the modewb. The flagb"has no effect on POSIX systems, but on Windows it disables special handling of '\n' and '\x1A'."7 Without it, a Windows program writes each LF as CRLF, so CRLF becomes CR CR LF. Both functions return anenum csv_status. - C++.
format_csvreturns astd::string.write_csvwrites it with anstd::ofstreamin binary mode, for the same reason as in C. A wrong number of fields throwscsv_error, and a file that cannot be written throwsstd::ios_base::failure.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl. Each case gives the records and the text that format_csv must return.
simpleandheader-only: plain fields, and a file with only a header.commaanddouble-quote:Lovelace, Adais written as"Lovelace, Ada". A double quote in a field is written twice.only-a-quote: the field"is written as"""".newline-in-field,crlf-in-fieldandcr-in-field: a field with an LF, a CRLF or a lone CR is quoted, and its line breaks are written as they are.empty-fieldsandone-empty-field: in a record with more than one field, an empty field is written as nothing, soa,,bhas an empty field in the middle. A record with one empty field is written as"".spaces:xkeeps its spaces and has no quotes.no-records: the text is empty.non-ascii:Zürichand東京are written as they are, and the file holds them as UTF-8.
The cases in cases/errors.jsonl must give the error field-count: a record with too many fields and a record with too few. The toolchain does not load this file yet, so the test files hold these cases by name. Each test file also writes a file to a temporary directory and checks its bytes.
Pitfalls
- Joining fields with commas breaks a field that holds a comma. The join does not add quotes, so a reader finds one field more than you wrote:
This code runs but gives a wrong answer on purpose.
import csv
import io
records = [["name", "born"], ["Lovelace, Ada", "1815"]]
text = "".join(",".join(record) + "\r\n" for record in records)
print(list(csv.reader(io.StringIO(text, newline=""))))
[['name', 'born'], ['Lovelace', ' Ada', '1815']]
A field with a double quote or a line break breaks the same way. Quote the fields as the solutions do, or use a CSV writer.
- Go's
csv.Writerchanges some fields. "As returned by NewWriter, a Writer writes records terminated by a newline".8 "If Writer.UseCRLF is true, the Writer ends each output line with \r\n instead of \n."8 WithUseCRLF, the writer also changes an LF inside a quoted field to CRLF, and it drops a lone CR. It writes a record with one empty field as an empty line, and it quotes a field that starts with a space:
This code runs but gives a wrong answer on purpose.
package main
import (
"encoding/csv"
"fmt"
"strings"
)
func main() {
var b strings.Builder
w := csv.NewWriter(&b)
w.UseCRLF = true
w.WriteAll([][]string{{"note"}, {""}, {"a\rb"}, {"c\nd"}, {" x"}})
fmt.Printf("%q\n", b.String())
}
"note\r\n\r\n\"ab\"\r\n\"c\r\nd\"\r\n\" x\"\r\n"
A reader then reads ab and c\r\nd, and "Blank lines are ignored."8 So one record is lost. If you use csv.Writer, remember that "The writes of individual records are buffered."8 Call Flush and then check Error.
-
Python needs
newline=''on the file. The csv module writes its own line breaks. "If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n line endings on write an extra \r will be added."2 On Windows, a file opened with the defaultnewlinechanges each\nto\r\n, so each CRLF of the writer becomes CR CR LF. -
utf-8-sigwrites a byte order mark. "On encoding the utf-8-sig codec will write 0xef, 0xbb, 0xbf as the first three bytes to the file."9 A reader that does not remove them finds U+FEFF in the first name of the header, as Read a CSV file shows. The solutions write no byte order mark. Add one only when the program that reads the file needs it. -
A field can be a formula in a spreadsheet. "When a spreadsheet program such as Microsoft Excel or LibreOffice Calc is used to open a CSV, any cells starting with = will be interpreted by the software as a formula."10 OWASP lists
=,+,-,@, tab, CR and LF as dangerous first characters.10 Quotes do not stop this. If the fields come from users and the file goes to a spreadsheet, escape these fields as CSV describes. The solutions do not, because the escape changes the data for a program that reads the file. -
A record with a different number of fields gives a bad file. A reader that checks the count rejects it. For Go's
csv.Reader, "If FieldsPerRecord is 0, Read sets it to the number of fields in the first record, so that future records must have the same field count."8 Check the count before you write, as the solutions do. Then an error leaves no half-written file.
Related tasks
- Read a CSV file: read the file back into records.
- CSV: the format, its history, its dialects and its security risks.
- Write a file: write text to a file.
- Read and write JSON: write a data format that has types and nesting.
- Sort a list of records: sort the records before you write them.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-csv-file/.
"""Writes records as a CSV file of RFC 4180."""
import csv
import io
class CsvError(ValueError):
"""A record has more or fewer fields than the first record (the header)."""
def __init__(self, record: int, got: int, want: int) -> None:
super().__init__(f"record {record} has {got} fields, the header has {want}")
self.kind = "field-count"
def _check(records: list[list[str]]) -> None:
for n, record in enumerate(records):
if len(record) != len(records[0]):
raise CsvError(n, len(record), len(records[0]))
def format_csv(records: list[list[str]]) -> str:
"""Returns the CSV text of the records. The first record is the header."""
_check(records)
out = io.StringIO(newline="")
# The default dialect "excel" ends each record with CRLF and quotes a field
# only when it holds a comma, a double quote, CR or LF.
csv.writer(out).writerows(records)
return out.getvalue()
def write_csv(path: str, records: list[list[str]]) -> None:
"""Writes the records to the file at path as UTF-8, with no byte order mark."""
_check(records)
# newline="" stops the file object from changing the line breaks.
with open(path, "w", encoding="utf-8", newline="") as f:
csv.writer(f).writerows(records)
test_write_csv.py 58 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-csv-file/.
import csv
from pathlib import Path
import pytest
from write_csv import CsvError, format_csv, write_csv
# name: (records, the CSV text)
CASES = {
"simple": ([["name", "age"], ["Ada", "36"], ["Alan", "41"]], "name,age\r\nAda,36\r\nAlan,41\r\n"),
"comma": ([["name", "born"], ["Lovelace, Ada", "1815"]], "name,born\r\n\"Lovelace, Ada\",1815\r\n"),
"double-quote": ([["id", "quote"], ["1", "She said \"hi\"."]], "id,quote\r\n1,\"She said \"\"hi\"\".\"\r\n"),
"only-a-quote": ([["q"], ["\""]], "q\r\n\"\"\"\"\r\n"),
"header-only": ([["name", "age"]], "name,age\r\n"),
"newline-in-field": ([["id", "address"], ["1", "12 High St\nLeeds"]], "id,address\r\n1,\"12 High St\nLeeds\"\r\n"),
"crlf-in-field": ([["id", "address"], ["1", "12 High St\r\nLeeds"]], "id,address\r\n1,\"12 High St\r\nLeeds\"\r\n"),
"cr-in-field": ([["id", "text"], ["1", "a\rb"]], "id,text\r\n1,\"a\rb\"\r\n"),
"empty-fields": ([["a", "b", "c"], ["", "", ""]], "a,b,c\r\n,,\r\n"),
"one-empty-field": ([["note"], [""], ["x"]], "note\r\n\"\"\r\nx\r\n"),
"spaces": ([["a", "b"], [" x ", " y"]], "a,b\r\n x , y\r\n"),
"no-records": ([], ""),
"non-ascii": ([["city"], ["Zürich"], ["東京"]], "city\r\nZürich\r\n東京\r\n"),
}
ERRORS = {
"too-many-fields": [["a", "b"], ["1", "2", "3"]],
"too-few-fields": [["a", "b"], ["1"]],
}
@pytest.mark.parametrize("name", CASES)
def test_format(name: str) -> None:
records, want = CASES[name]
assert format_csv(records) == want
@pytest.mark.parametrize("name", CASES)
def test_write_and_read_back(name: str, tmp_path: Path) -> None:
records, want = CASES[name]
path = tmp_path / "out.csv"
write_csv(str(path), records)
assert path.read_bytes() == want.encode("utf-8")
with open(path, encoding="utf-8", newline="") as f:
assert list(csv.reader(f)) == records
@pytest.mark.parametrize("name", ERRORS)
def test_field_count(name: str, tmp_path: Path) -> None:
with pytest.raises(CsvError) as e:
format_csv(ERRORS[name])
assert e.value.kind == "field-count"
path = tmp_path / "out.csv"
with pytest.raises(CsvError):
write_csv(str(path), ERRORS[name])
assert not path.exists()
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
#include "write_csv.hpp"
#include <fstream>
namespace {
// A record with one empty field needs quotes, or the line is empty and a reader skips it.
bool needs_quotes(const std::string& field, bool alone) {
return (alone && field.empty()) || field.find_first_of(",\"\r\n") != std::string::npos;
}
} // namespace
std::string format_csv(const std::vector<std::vector<std::string>>& records) {
std::string out;
for (std::size_t n = 0; n < records.size(); n++) {
const auto& record = records[n];
if (record.size() != records[0].size()) {
throw csv_error("record " + std::to_string(n) + " has " + std::to_string(record.size()) +
" fields, the header has " + std::to_string(records[0].size()));
}
for (std::size_t i = 0; i < record.size(); i++) {
if (i > 0) {
out += ',';
}
const std::string& field = record[i];
if (needs_quotes(field, record.size() == 1)) {
out += '"';
for (char c : field) {
if (c == '"') {
out += '"';
}
out += c;
}
out += '"';
} else {
out += field;
}
}
out += "\r\n";
}
return out;
}
void write_csv(const std::string& path, const std::vector<std::vector<std::string>>& records) {
std::string text = format_csv(records);
// Binary mode: on Windows, text mode would write each LF as CRLF, also inside a field.
std::ofstream f(path, std::ios::binary);
f.exceptions(std::ios::failbit | std::ios::badbit);
f.write(text.data(), static_cast<std::streamsize>(text.size()));
f.close();
}
write_csv.hpp 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
#ifndef WRITE_CSV_HPP
#define WRITE_CSV_HPP
#include <stdexcept>
#include <string>
#include <vector>
// A record has more or fewer fields than the first record (the header).
class csv_error : public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};
// Returns the CSV text of the records. The first record is the header.
std::string format_csv(const std::vector<std::vector<std::string>>& records);
// Writes the records to the file at path as UTF-8, with no byte order mark.
// Throws csv_error for a bad record and std::ios_base::failure if the file cannot be written.
void write_csv(const std::string& path, const std::vector<std::vector<std::string>>& records);
#endif
test_write_csv.cpp 77 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
#include "write_csv.hpp"
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using rows = std::vector<std::vector<std::string>>;
struct test_case {
const char* name;
rows records;
std::string want;
};
int main() {
const std::vector<test_case> cases = {
{"simple", {{"name", "age"}, {"Ada", "36"}, {"Alan", "41"}}, "name,age\r\nAda,36\r\nAlan,41\r\n"},
{"comma", {{"name", "born"}, {"Lovelace, Ada", "1815"}}, "name,born\r\n\"Lovelace, Ada\",1815\r\n"},
{"double-quote", {{"id", "quote"}, {"1", "She said \"hi\"."}}, "id,quote\r\n1,\"She said \"\"hi\"\".\"\r\n"},
{"only-a-quote", {{"q"}, {"\""}}, "q\r\n\"\"\"\"\r\n"},
{"header-only", {{"name", "age"}}, "name,age\r\n"},
{"newline-in-field", {{"id", "address"}, {"1", "12 High St\nLeeds"}}, "id,address\r\n1,\"12 High St\nLeeds\"\r\n"},
{"crlf-in-field", {{"id", "address"}, {"1", "12 High St\r\nLeeds"}}, "id,address\r\n1,\"12 High St\r\nLeeds\"\r\n"},
{"cr-in-field", {{"id", "text"}, {"1", "a\rb"}}, "id,text\r\n1,\"a\rb\"\r\n"},
{"empty-fields", {{"a", "b", "c"}, {"", "", ""}}, "a,b,c\r\n,,\r\n"},
{"one-empty-field", {{"note"}, {""}, {"x"}}, "note\r\n\"\"\r\nx\r\n"},
{"spaces", {{"a", "b"}, {" x ", " y"}}, "a,b\r\n x , y\r\n"},
{"no-records", {}, ""},
{"non-ascii", {{"city"}, {"Z\xc3\xbcrich"}, {"\xe6\x9d\xb1\xe4\xba\xac"}}, "city\r\nZ\xc3\xbcrich\r\n\xe6\x9d\xb1\xe4\xba\xac\r\n"},
};
const std::vector<std::pair<const char*, rows>> errors = {
{"too-many-fields", {{"a", "b"}, {"1", "2", "3"}}},
{"too-few-fields", {{"a", "b"}, {"1"}}},
};
const std::string path = (std::filesystem::temp_directory_path() / "write-csv-test.csv").string();
int failed = 0;
for (const auto& t : cases) {
bool ok = format_csv(t.records) == t.want;
write_csv(path, t.records);
std::ifstream in(path, std::ios::binary);
std::string data((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
ok = ok && data == t.want;
if (!ok) {
std::cout << "FAIL " << t.name << "\n";
failed++;
}
}
for (const auto& [name, records] : errors) {
std::remove(path.c_str());
bool ok = false;
try {
format_csv(records);
} catch (const csv_error&) {
ok = true;
}
try {
write_csv(path, records);
ok = false;
} catch (const csv_error&) {
}
ok = ok && !std::filesystem::exists(path);
if (!ok) {
std::cout << "FAIL " << name << "\n";
failed++;
}
}
std::remove(path.c_str());
std::cout << (failed ? "FAILED" : "all tests passed") << "\n";
return failed != 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
/** Writes records as a CSV file of RFC 4180. The JDK has no CSV writer, so this class has a small one. */
public final class WriteCsv {
private WriteCsv() {}
/** A record has more or fewer fields than the first record (the header). */
public static final class CsvException extends IllegalArgumentException {
private static final long serialVersionUID = 1L;
CsvException(int record, int got, int want) {
super("record " + record + " has " + got + " fields, the header has " + want);
}
public String kind() {
return "field-count";
}
}
private static boolean needsQuotes(String field, boolean alone) {
// A record with one empty field needs quotes, or the line is empty and a reader skips it.
if (alone && field.isEmpty()) {
return true;
}
for (int i = 0; i < field.length(); i++) {
char c = field.charAt(i);
if (c == ',' || c == '"' || c == '\r' || c == '\n') {
return true;
}
}
return false;
}
/** Returns the CSV text of the records. The first record is the header. */
public static String formatCsv(List<List<String>> records) {
StringBuilder out = new StringBuilder();
for (int n = 0; n < records.size(); n++) {
List<String> record = records.get(n);
if (record.size() != records.get(0).size()) {
throw new CsvException(n, record.size(), records.get(0).size());
}
for (int i = 0; i < record.size(); i++) {
if (i > 0) {
out.append(',');
}
String field = record.get(i);
if (needsQuotes(field, record.size() == 1)) {
out.append('"').append(field.replace("\"", "\"\"")).append('"');
} else {
out.append(field);
}
}
out.append("\r\n");
}
return out.toString();
}
/** Writes the records to the file at path as UTF-8, with no byte order mark. */
public static void writeCsv(Path path, List<List<String>> records) throws IOException {
Files.writeString(path, formatCsv(records));
}
}
WriteCsvTest.java 64 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
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.Path;
import java.util.List;
import java.util.stream.Stream;
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 WriteCsvTest {
@TempDir Path dir;
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("simple", List.of(List.of("name", "age"), List.of("Ada", "36"), List.of("Alan", "41")), "name,age\r\nAda,36\r\nAlan,41\r\n"),
Arguments.of("comma", List.of(List.of("name", "born"), List.of("Lovelace, Ada", "1815")), "name,born\r\n\"Lovelace, Ada\",1815\r\n"),
Arguments.of("double-quote", List.of(List.of("id", "quote"), List.of("1", "She said \"hi\".")), "id,quote\r\n1,\"She said \"\"hi\"\".\"\r\n"),
Arguments.of("only-a-quote", List.of(List.of("q"), List.of("\"")), "q\r\n\"\"\"\"\r\n"),
Arguments.of("header-only", List.of(List.of("name", "age")), "name,age\r\n"),
Arguments.of("newline-in-field", List.of(List.of("id", "address"), List.of("1", "12 High St\nLeeds")), "id,address\r\n1,\"12 High St\nLeeds\"\r\n"),
Arguments.of("crlf-in-field", List.of(List.of("id", "address"), List.of("1", "12 High St\r\nLeeds")), "id,address\r\n1,\"12 High St\r\nLeeds\"\r\n"),
Arguments.of("cr-in-field", List.of(List.of("id", "text"), List.of("1", "a\rb")), "id,text\r\n1,\"a\rb\"\r\n"),
Arguments.of("empty-fields", List.of(List.of("a", "b", "c"), List.of("", "", "")), "a,b,c\r\n,,\r\n"),
Arguments.of("one-empty-field", List.of(List.of("note"), List.of(""), List.of("x")), "note\r\n\"\"\r\nx\r\n"),
Arguments.of("spaces", List.of(List.of("a", "b"), List.of(" x ", " y")), "a,b\r\n x , y\r\n"),
Arguments.of("no-records", List.of(), ""),
Arguments.of("non-ascii", List.of(List.of("city"), List.of("Zürich"), List.of("東京")), "city\r\nZürich\r\n東京\r\n"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void formatAndWrite(String name, List<List<String>> records, String want) throws IOException {
assertEquals(want, WriteCsv.formatCsv(records));
Path path = dir.resolve(name + ".csv");
WriteCsv.writeCsv(path, records);
assertArrayEquals(want.getBytes(StandardCharsets.UTF_8), Files.readAllBytes(path));
}
static Stream<Arguments> errors() {
return Stream.of(
Arguments.of("too-many-fields", List.of(List.of("a", "b"), List.of("1", "2", "3"))),
Arguments.of("too-few-fields", List.of(List.of("a", "b"), List.of("1"))));
}
@ParameterizedTest(name = "{0}")
@MethodSource("errors")
void fieldCount(String name, List<List<String>> records) {
var e = assertThrows(WriteCsv.CsvException.class, () -> WriteCsv.formatCsv(records));
assertEquals("field-count", e.kind());
Path path = dir.resolve(name + ".csv");
assertThrows(WriteCsv.CsvException.class, () -> WriteCsv.writeCsv(path, records));
assertFalse(Files.exists(path));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
#include "write_csv.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// A record with one empty field needs quotes, or the line is empty and a reader skips it.
static int needs_quotes(const char *field, int alone) {
return (alone && field[0] == '\0') || strpbrk(field, ",\"\r\n") != NULL;
}
enum csv_status format_csv(const char *const *const *records, const size_t *ncols, size_t nrecords, char **out) {
*out = NULL;
// The first pass checks the records and counts the bytes (one more for each field, for a comma), and the second pass writes them.
size_t size = 1;
for (size_t r = 0; r < nrecords; r++) {
if (ncols[r] != ncols[0]) {
return CSV_ERR_FIELD_COUNT;
}
for (size_t c = 0; c < ncols[r]; c++) {
const char *f = records[r][c];
size += strlen(f) + 1;
if (needs_quotes(f, ncols[r] == 1)) {
size += 2;
for (const char *p = f; *p; p++) {
size += *p == '"';
}
}
}
size += 2; // CRLF
}
char *buf = malloc(size);
if (buf == NULL) {
return CSV_ERR_MEMORY;
}
char *w = buf;
for (size_t r = 0; r < nrecords; r++) {
for (size_t c = 0; c < ncols[r]; c++) {
const char *f = records[r][c];
if (c > 0) {
*w++ = ',';
}
if (needs_quotes(f, ncols[r] == 1)) {
*w++ = '"';
for (const char *p = f; *p; p++) {
if (*p == '"') {
*w++ = '"';
}
*w++ = *p;
}
*w++ = '"';
} else {
size_t n = strlen(f);
memcpy(w, f, n);
w += n;
}
}
*w++ = '\r';
*w++ = '\n';
}
*w = '\0';
*out = buf;
return CSV_OK;
}
enum csv_status write_csv(const char *path, const char *const *const *records, const size_t *ncols, size_t nrecords) {
char *text;
enum csv_status st = format_csv(records, ncols, nrecords, &text);
if (st != CSV_OK) {
return st;
}
// "wb": on Windows, text mode would write each LF as CRLF, also inside a field.
FILE *f = fopen(path, "wb");
if (f == NULL) {
free(text);
return CSV_ERR_IO;
}
size_t n = strlen(text);
int ok = fwrite(text, 1, n, f) == n;
ok = fclose(f) == 0 && ok;
free(text);
return ok ? CSV_OK : CSV_ERR_IO;
}
write_csv.h 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
#ifndef WRITE_CSV_H
#define WRITE_CSV_H
#include <stddef.h>
enum csv_status {
CSV_OK = 0,
CSV_ERR_IO, // the file cannot be written; errno tells why
CSV_ERR_FIELD_COUNT, // a record has more or fewer fields than the first record (the header)
CSV_ERR_MEMORY,
};
// nrecords records of ncols[r] fields each. records[r][c] is a NUL-terminated UTF-8 string.
// On success, *out is the CSV text, which the caller frees with free.
enum csv_status format_csv(const char *const *const *records, const size_t *ncols, size_t nrecords, char **out);
// Writes the CSV text of the records to the file at path, with no byte order mark.
enum csv_status write_csv(const char *path, const char *const *const *records, const size_t *ncols, size_t nrecords);
#endif
test_write_csv.c 89 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
#define _POSIX_C_SOURCE 200809L
#include "write_csv.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAXR 3
#define MAXC 3
struct test_case {
const char *name;
size_t nrecords;
size_t ncols[MAXR];
const char *records[MAXR][MAXC];
const char *want;
};
static const struct test_case cases[] = {
{"simple", 3, {2, 2, 2}, {{"name", "age"}, {"Ada", "36"}, {"Alan", "41"}}, "name,age\r\nAda,36\r\nAlan,41\r\n"},
{"comma", 2, {2, 2}, {{"name", "born"}, {"Lovelace, Ada", "1815"}}, "name,born\r\n\"Lovelace, Ada\",1815\r\n"},
{"double-quote", 2, {2, 2}, {{"id", "quote"}, {"1", "She said \"hi\"."}}, "id,quote\r\n1,\"She said \"\"hi\"\".\"\r\n"},
{"only-a-quote", 2, {1, 1}, {{"q"}, {"\""}}, "q\r\n\"\"\"\"\r\n"},
{"header-only", 1, {2}, {{"name", "age"}}, "name,age\r\n"},
{"newline-in-field", 2, {2, 2}, {{"id", "address"}, {"1", "12 High St\nLeeds"}}, "id,address\r\n1,\"12 High St\nLeeds\"\r\n"},
{"crlf-in-field", 2, {2, 2}, {{"id", "address"}, {"1", "12 High St\r\nLeeds"}}, "id,address\r\n1,\"12 High St\r\nLeeds\"\r\n"},
{"cr-in-field", 2, {2, 2}, {{"id", "text"}, {"1", "a\rb"}}, "id,text\r\n1,\"a\rb\"\r\n"},
{"empty-fields", 2, {3, 3}, {{"a", "b", "c"}, {"", "", ""}}, "a,b,c\r\n,,\r\n"},
{"one-empty-field", 3, {1, 1, 1}, {{"note"}, {""}, {"x"}}, "note\r\n\"\"\r\nx\r\n"},
{"spaces", 2, {2, 2}, {{"a", "b"}, {" x ", " y"}}, "a,b\r\n x , y\r\n"},
{"no-records", 0, {0}, {{NULL}}, ""},
{"non-ascii", 3, {1, 1, 1}, {{"city"}, {"Z\xc3\xbcrich"}, {"\xe6\x9d\xb1\xe4\xba\xac"}}, "city\r\nZ\xc3\xbcrich\r\n\xe6\x9d\xb1\xe4\xba\xac\r\n"},
{"too-many-fields", 2, {2, 3}, {{"a", "b"}, {"1", "2", "3"}}, NULL},
{"too-few-fields", 2, {2, 1}, {{"a", "b"}, {"1"}}, NULL},
};
static char *read_file(const char *path) {
FILE *f = fopen(path, "rb");
if (f == NULL) {
return NULL;
}
char *buf = calloc(1, 4096);
size_t n = buf ? fread(buf, 1, 4095, f) : 0;
(void)n;
fclose(f);
return buf;
}
int main(void) {
int failed = 0;
char path[] = "/tmp/write-csv-XXXXXX";
int fd = mkstemp(path);
if (fd < 0) {
perror("mkstemp");
return 1;
}
close(fd);
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
const struct test_case *t = &cases[i];
const char *const *rows[MAXR];
for (size_t r = 0; r < MAXR; r++) {
rows[r] = t->records[r];
}
char *got = NULL;
enum csv_status st = format_csv(rows, t->ncols, t->nrecords, &got);
int ok;
if (t->want == NULL) {
ok = st == CSV_ERR_FIELD_COUNT && got == NULL && write_csv(path, rows, t->ncols, t->nrecords) == CSV_ERR_FIELD_COUNT;
} else {
ok = st == CSV_OK && strcmp(got, t->want) == 0 && write_csv(path, rows, t->ncols, t->nrecords) == CSV_OK;
char *data = ok ? read_file(path) : NULL;
ok = ok && data != NULL && strcmp(data, t->want) == 0;
free(data);
}
free(got);
if (!ok) {
printf("FAIL %s\n", t->name);
failed++;
}
}
unlink(path);
printf("%s\n", failed ? "FAILED" : "all tests passed");
return failed != 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
using System.Text;
/// <summary>A record has more or fewer fields than the first record (the header).</summary>
public sealed class CsvException(string message) : FormatException(message)
{
public string Kind => "field-count";
}
/// <summary>Writes records as a CSV file of RFC 4180. .NET has no CSV writer, so this class has a small one.</summary>
public static class WriteCsv
{
private static readonly char[] Special = [',', '"', '\r', '\n'];
/// <summary>Returns the CSV text of the records. The first record is the header.</summary>
/// <exception cref="CsvException">a record with the wrong number of fields.</exception>
public static string Format(IReadOnlyList<IReadOnlyList<string>> records)
{
var out_ = new StringBuilder();
for (int n = 0; n < records.Count; n++)
{
IReadOnlyList<string> record = records[n];
if (record.Count != records[0].Count)
{
throw new CsvException($"record {n} has {record.Count} fields, the header has {records[0].Count}");
}
for (int i = 0; i < record.Count; i++)
{
if (i > 0)
{
out_.Append(',');
}
string field = record[i];
// A record with one empty field needs quotes, or the line is empty and a reader skips it.
if (field.IndexOfAny(Special) >= 0 || (record.Count == 1 && field.Length == 0))
{
out_.Append('"').Append(field.Replace("\"", "\"\"")).Append('"');
}
else
{
out_.Append(field);
}
}
out_.Append("\r\n");
}
return out_.ToString();
}
/// <summary>Writes the records to the file at path as UTF-8, with no byte order mark.</summary>
public static void Write(string path, IReadOnlyList<IReadOnlyList<string>> records)
{
// WriteAllText(string, string) writes UTF-8 without a byte order mark.
File.WriteAllText(path, Format(records));
}
}
WriteCsvTests.cs 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
using System.Text;
using Xunit;
public sealed class WriteCsvTests : IDisposable
{
private readonly string dir = Directory.CreateTempSubdirectory("write-csv-").FullName;
public void Dispose() => Directory.Delete(dir, recursive: true);
// Each record is written with its fields joined by "|", so that TheoryData can hold it.
public static TheoryData<string, string[], string> Cases => new()
{
{ "simple", ["name|age", "Ada|36", "Alan|41"], "name,age\r\nAda,36\r\nAlan,41\r\n" },
{ "comma", ["name|born", "Lovelace, Ada|1815"], "name,born\r\n\"Lovelace, Ada\",1815\r\n" },
{ "double-quote", ["id|quote", "1|She said \"hi\"."], "id,quote\r\n1,\"She said \"\"hi\"\".\"\r\n" },
{ "only-a-quote", ["q", "\""], "q\r\n\"\"\"\"\r\n" },
{ "header-only", ["name|age"], "name,age\r\n" },
{ "newline-in-field", ["id|address", "1|12 High St\nLeeds"], "id,address\r\n1,\"12 High St\nLeeds\"\r\n" },
{ "crlf-in-field", ["id|address", "1|12 High St\r\nLeeds"], "id,address\r\n1,\"12 High St\r\nLeeds\"\r\n" },
{ "cr-in-field", ["id|text", "1|a\rb"], "id,text\r\n1,\"a\rb\"\r\n" },
{ "empty-fields", ["a|b|c", "||"], "a,b,c\r\n,,\r\n" },
{ "one-empty-field", ["note", "", "x"], "note\r\n\"\"\r\nx\r\n" },
{ "spaces", ["a|b", " x | y"], "a,b\r\n x , y\r\n" },
{ "no-records", [], "" },
{ "non-ascii", ["city", "Zürich", "東京"], "city\r\nZürich\r\n東京\r\n" },
};
private static List<IReadOnlyList<string>> Records(string[] rows) => rows.Select(r => (IReadOnlyList<string>)r.Split('|')).ToList();
[Theory]
[MemberData(nameof(Cases))]
public void FormatAndWrite(string name, string[] rows, string want)
{
var records = Records(rows);
Assert.Equal(want, WriteCsv.Format(records));
string path = Path.Combine(dir, name + ".csv");
WriteCsv.Write(path, records);
Assert.Equal(Encoding.UTF8.GetBytes(want), File.ReadAllBytes(path));
}
[Theory]
[InlineData("too-many-fields", new[] { "a|b", "1|2|3" })]
[InlineData("too-few-fields", new[] { "a|b", "1" })]
public void FieldCount(string name, string[] rows)
{
var records = Records(rows);
Assert.Equal("field-count", Assert.Throws<CsvException>(() => WriteCsv.Format(records)).Kind);
string path = Path.Combine(dir, name + ".csv");
Assert.Throws<CsvException>(() => WriteCsv.Write(path, records));
Assert.False(File.Exists(path));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
// Writes records as a CSV file of RFC 4180. Node.js has no CSV writer, so this file has a small one.
import { writeFileSync } from "node:fs";
/** A record has more or fewer fields than the first record (the header). */
export class CsvError extends Error {
constructor(record, got, want) {
super(`record ${record} has ${got} fields, the header has ${want}`);
this.name = "CsvError";
this.kind = "field-count";
}
}
const SPECIAL = /[",\r\n]/;
function formatField(field, alone) {
// A record with one empty field needs quotes, or the line is empty and a reader skips it.
if (SPECIAL.test(field) || (alone && field === "")) {
return `"${field.replaceAll('"', '""')}"`;
}
return field;
}
/** Returns the CSV text of the records. The first record is the header. */
export function formatCsv(records) {
let out = "";
for (const [n, record] of records.entries()) {
if (record.length !== records[0].length) {
throw new CsvError(n, record.length, records[0].length);
}
out += record.map((field) => formatField(field, record.length === 1)).join(",") + "\r\n";
}
return out;
}
/** Writes the records to the file at path as UTF-8, with no byte order mark. */
export function writeCsv(path, records) {
writeFileSync(path, formatCsv(records), "utf8");
}
writeCsv.test.js 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
import assert from "node:assert/strict";
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";
import { CsvError, formatCsv, writeCsv } from "./writeCsv.js";
const CASES = {
simple: [[["name", "age"], ["Ada", "36"], ["Alan", "41"]], "name,age\r\nAda,36\r\nAlan,41\r\n"],
comma: [[["name", "born"], ["Lovelace, Ada", "1815"]], 'name,born\r\n"Lovelace, Ada",1815\r\n'],
"double-quote": [[["id", "quote"], ["1", 'She said "hi".']], 'id,quote\r\n1,"She said ""hi""."\r\n'],
"only-a-quote": [[["q"], ['"']], 'q\r\n""""\r\n'],
"header-only": [[["name", "age"]], "name,age\r\n"],
"newline-in-field": [[["id", "address"], ["1", "12 High St\nLeeds"]], 'id,address\r\n1,"12 High St\nLeeds"\r\n'],
"crlf-in-field": [[["id", "address"], ["1", "12 High St\r\nLeeds"]], 'id,address\r\n1,"12 High St\r\nLeeds"\r\n'],
"cr-in-field": [[["id", "text"], ["1", "a\rb"]], 'id,text\r\n1,"a\rb"\r\n'],
"empty-fields": [[["a", "b", "c"], ["", "", ""]], "a,b,c\r\n,,\r\n"],
"one-empty-field": [[["note"], [""], ["x"]], 'note\r\n""\r\nx\r\n'],
spaces: [[["a", "b"], [" x ", " y"]], "a,b\r\n x , y\r\n"],
"no-records": [[], ""],
"non-ascii": [[["city"], ["Zürich"], ["東京"]], "city\r\nZürich\r\n東京\r\n"],
};
const ERRORS = {
"too-many-fields": [["a", "b"], ["1", "2", "3"]],
"too-few-fields": [["a", "b"], ["1"]],
};
const dir = mkdtempSync(join(tmpdir(), "write-csv-"));
after(() => rmSync(dir, { recursive: true, force: true }));
for (const [name, [records, want]] of Object.entries(CASES)) {
test(name, () => {
assert.equal(formatCsv(records), want);
const path = join(dir, `${name}.csv`);
writeCsv(path, records);
assert.deepEqual(readFileSync(path), Buffer.from(want, "utf8"));
});
}
for (const [name, records] of Object.entries(ERRORS)) {
test(name, () => {
assert.throws(() => formatCsv(records), (e) => e instanceof CsvError && e.kind === "field-count");
const path = join(dir, `${name}.csv`);
assert.throws(() => writeCsv(path, records), CsvError);
assert.equal(existsSync(path), false);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
// Writes records as a CSV file of RFC 4180. Node.js has no CSV writer, so this file has a small one.
import { writeFileSync } from "node:fs";
/** A record has more or fewer fields than the first record (the header). */
export class CsvError extends Error {
readonly kind = "field-count";
constructor(record: number, got: number, want: number) {
super(`record ${record} has ${got} fields, the header has ${want}`);
this.name = "CsvError";
}
}
const SPECIAL = /[",\r\n]/;
function formatField(field: string, alone: boolean): string {
// A record with one empty field needs quotes, or the line is empty and a reader skips it.
if (SPECIAL.test(field) || (alone && field === "")) {
return `"${field.replaceAll('"', '""')}"`;
}
return field;
}
/** Returns the CSV text of the records. The first record is the header. */
export function formatCsv(records: readonly (readonly string[])[]): string {
let out = "";
for (const [n, record] of records.entries()) {
if (record.length !== records[0].length) {
throw new CsvError(n, record.length, records[0].length);
}
out += record.map((field) => formatField(field, record.length === 1)).join(",") + "\r\n";
}
return out;
}
/** Writes the records to the file at path as UTF-8, with no byte order mark. */
export function writeCsv(path: string, records: readonly (readonly string[])[]): void {
writeFileSync(path, formatCsv(records), "utf8");
}
writeCsv.test.ts 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
import assert from "node:assert/strict";
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";
import { CsvError, formatCsv, writeCsv } from "./writeCsv.ts";
const CASES: Record<string, [string[][], string]> = {
simple: [[["name", "age"], ["Ada", "36"], ["Alan", "41"]], "name,age\r\nAda,36\r\nAlan,41\r\n"],
comma: [[["name", "born"], ["Lovelace, Ada", "1815"]], 'name,born\r\n"Lovelace, Ada",1815\r\n'],
"double-quote": [[["id", "quote"], ["1", 'She said "hi".']], 'id,quote\r\n1,"She said ""hi""."\r\n'],
"only-a-quote": [[["q"], ['"']], 'q\r\n""""\r\n'],
"header-only": [[["name", "age"]], "name,age\r\n"],
"newline-in-field": [[["id", "address"], ["1", "12 High St\nLeeds"]], 'id,address\r\n1,"12 High St\nLeeds"\r\n'],
"crlf-in-field": [[["id", "address"], ["1", "12 High St\r\nLeeds"]], 'id,address\r\n1,"12 High St\r\nLeeds"\r\n'],
"cr-in-field": [[["id", "text"], ["1", "a\rb"]], 'id,text\r\n1,"a\rb"\r\n'],
"empty-fields": [[["a", "b", "c"], ["", "", ""]], "a,b,c\r\n,,\r\n"],
"one-empty-field": [[["note"], [""], ["x"]], 'note\r\n""\r\nx\r\n'],
spaces: [[["a", "b"], [" x ", " y"]], "a,b\r\n x , y\r\n"],
"no-records": [[], ""],
"non-ascii": [[["city"], ["Zürich"], ["東京"]], "city\r\nZürich\r\n東京\r\n"],
};
const ERRORS: Record<string, string[][]> = {
"too-many-fields": [["a", "b"], ["1", "2", "3"]],
"too-few-fields": [["a", "b"], ["1"]],
};
const dir = mkdtempSync(join(tmpdir(), "write-csv-"));
after(() => rmSync(dir, { recursive: true, force: true }));
for (const [name, [records, want]] of Object.entries(CASES)) {
test(name, () => {
assert.equal(formatCsv(records), want);
const path = join(dir, `${name}.csv`);
writeCsv(path, records);
assert.deepEqual(readFileSync(path), Buffer.from(want, "utf8"));
});
}
for (const [name, records] of Object.entries(ERRORS)) {
test(name, () => {
assert.throws(() => formatCsv(records), (e: unknown) => e instanceof CsvError && e.kind === "field-count");
const path = join(dir, `${name}.csv`);
assert.throws(() => writeCsv(path, records), CsvError);
assert.equal(existsSync(path), false);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
// Package writecsv writes records as a CSV file of RFC 4180.
package writecsv
import (
"fmt"
"os"
"strings"
)
// FieldCountError reports a record with more or fewer fields than the header.
type FieldCountError struct {
Record, Got, Want int
}
func (e *FieldCountError) Error() string {
return fmt.Sprintf("record %d has %d fields, the header has %d", e.Record, e.Got, e.Want)
}
// FormatCSV returns the CSV text of the records. The first record is the header.
// It does not use csv.Writer from encoding/csv, because that writer writes a
// record with one empty field as an empty line and changes line breaks in fields.
func FormatCSV(records [][]string) (string, error) {
var b strings.Builder
for n, record := range records {
if len(record) != len(records[0]) {
return "", &FieldCountError{n, len(record), len(records[0])}
}
for i, field := range record {
if i > 0 {
b.WriteByte(',')
}
// A record with one empty field needs quotes, or the line is empty and a reader skips it.
if strings.ContainsAny(field, ",\"\r\n") || (len(record) == 1 && field == "") {
b.WriteByte('"')
b.WriteString(strings.ReplaceAll(field, `"`, `""`))
b.WriteByte('"')
} else {
b.WriteString(field)
}
}
b.WriteString("\r\n")
}
return b.String(), nil
}
// WriteCSV writes the records to the file at path as UTF-8, with no byte order mark.
func WriteCSV(path string, records [][]string) error {
text, err := FormatCSV(records)
if err != nil {
return err
}
return os.WriteFile(path, []byte(text), 0o644)
}
write_csv_test.go 73 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
package writecsv
import (
"errors"
"os"
"path/filepath"
"testing"
)
type rows = [][]string
var cases = []struct {
name string
records rows
want string
}{
{"simple", rows{{"name", "age"}, {"Ada", "36"}, {"Alan", "41"}}, "name,age\r\nAda,36\r\nAlan,41\r\n"},
{"comma", rows{{"name", "born"}, {"Lovelace, Ada", "1815"}}, "name,born\r\n\"Lovelace, Ada\",1815\r\n"},
{"double-quote", rows{{"id", "quote"}, {"1", "She said \"hi\"."}}, "id,quote\r\n1,\"She said \"\"hi\"\".\"\r\n"},
{"only-a-quote", rows{{"q"}, {"\""}}, "q\r\n\"\"\"\"\r\n"},
{"header-only", rows{{"name", "age"}}, "name,age\r\n"},
{"newline-in-field", rows{{"id", "address"}, {"1", "12 High St\nLeeds"}}, "id,address\r\n1,\"12 High St\nLeeds\"\r\n"},
{"crlf-in-field", rows{{"id", "address"}, {"1", "12 High St\r\nLeeds"}}, "id,address\r\n1,\"12 High St\r\nLeeds\"\r\n"},
{"cr-in-field", rows{{"id", "text"}, {"1", "a\rb"}}, "id,text\r\n1,\"a\rb\"\r\n"},
{"empty-fields", rows{{"a", "b", "c"}, {"", "", ""}}, "a,b,c\r\n,,\r\n"},
{"one-empty-field", rows{{"note"}, {""}, {"x"}}, "note\r\n\"\"\r\nx\r\n"},
{"spaces", rows{{"a", "b"}, {" x ", " y"}}, "a,b\r\n x , y\r\n"},
{"no-records", rows{}, ""},
{"non-ascii", rows{{"city"}, {"Zürich"}, {"東京"}}, "city\r\nZürich\r\n東京\r\n"},
}
func TestFormatAndWrite(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, err := FormatCSV(c.records)
if err != nil || got != c.want {
t.Fatalf("FormatCSV = %q, %v; want %q", got, err, c.want)
}
path := filepath.Join(t.TempDir(), "out.csv")
if err := WriteCSV(path, c.records); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(path)
if err != nil || string(data) != c.want {
t.Fatalf("file = %q, %v; want %q", data, err, c.want)
}
})
}
}
func TestFieldCount(t *testing.T) {
for name, records := range map[string]rows{
"too-many-fields": {{"a", "b"}, {"1", "2", "3"}},
"too-few-fields": {{"a", "b"}, {"1"}},
} {
t.Run(name, func(t *testing.T) {
var fe *FieldCountError
if _, err := FormatCSV(records); !errors.As(err, &fe) {
t.Fatalf("FormatCSV error = %v; want a *FieldCountError", err)
}
path := filepath.Join(t.TempDir(), "out.csv")
if err := WriteCSV(path, records); !errors.As(err, &fe) {
t.Fatalf("WriteCSV error = %v; want a *FieldCountError", err)
}
if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("the file exists after an error: %v", err)
}
})
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
//! Writes records as a CSV file of RFC 4180. The standard library has no CSV writer, so this file has a small one.
use std::fmt;
use std::fs;
use std::io;
use std::path::Path;
/// The error for records that cannot be written.
#[derive(Debug)]
pub enum CsvError {
/// The file cannot be written.
Io(io::Error),
/// A record has more or fewer fields than the first record (the header).
FieldCount { record: usize, got: usize, want: usize },
}
impl fmt::Display for CsvError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CsvError::Io(e) => write!(f, "{e}"),
CsvError::FieldCount { record, got, want } => {
write!(f, "record {record} has {got} fields, the header has {want}")
}
}
}
}
impl std::error::Error for CsvError {}
fn needs_quotes(field: &str, alone: bool) -> bool {
// A record with one empty field needs quotes, or the line is empty and a reader skips it.
(alone && field.is_empty()) || field.contains([',', '"', '\r', '\n'])
}
/// Returns the CSV text of the records. The first record is the header.
pub fn format_csv<S: AsRef<str>>(records: &[Vec<S>]) -> Result<String, CsvError> {
let mut out = String::new();
for (n, record) in records.iter().enumerate() {
if record.len() != records[0].len() {
return Err(CsvError::FieldCount { record: n, got: record.len(), want: records[0].len() });
}
for (i, field) in record.iter().enumerate() {
let field = field.as_ref();
if i > 0 {
out.push(',');
}
if needs_quotes(field, record.len() == 1) {
out.push('"');
out.push_str(&field.replace('"', "\"\""));
out.push('"');
} else {
out.push_str(field);
}
}
out.push_str("\r\n");
}
Ok(out)
}
/// Writes the records to the file at path as UTF-8, with no byte order mark.
pub fn write_csv<S: AsRef<str>>(path: &Path, records: &[Vec<S>]) -> Result<(), CsvError> {
let text = format_csv(records)?;
fs::write(path, text).map_err(CsvError::Io)
}
tests/write_csv_test.rs 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-csv-file/.
use std::fs;
use algo_write_a_csv_file::{CsvError, format_csv, write_csv};
const CASES: &[(&str, &[&[&str]], &str)] = &[
("simple", &[&["name", "age"], &["Ada", "36"], &["Alan", "41"]], "name,age\r\nAda,36\r\nAlan,41\r\n"),
("comma", &[&["name", "born"], &["Lovelace, Ada", "1815"]], "name,born\r\n\"Lovelace, Ada\",1815\r\n"),
("double-quote", &[&["id", "quote"], &["1", "She said \"hi\"."]], "id,quote\r\n1,\"She said \"\"hi\"\".\"\r\n"),
("only-a-quote", &[&["q"], &["\""]], "q\r\n\"\"\"\"\r\n"),
("header-only", &[&["name", "age"]], "name,age\r\n"),
("newline-in-field", &[&["id", "address"], &["1", "12 High St\nLeeds"]], "id,address\r\n1,\"12 High St\nLeeds\"\r\n"),
("crlf-in-field", &[&["id", "address"], &["1", "12 High St\r\nLeeds"]], "id,address\r\n1,\"12 High St\r\nLeeds\"\r\n"),
("cr-in-field", &[&["id", "text"], &["1", "a\rb"]], "id,text\r\n1,\"a\rb\"\r\n"),
("empty-fields", &[&["a", "b", "c"], &["", "", ""]], "a,b,c\r\n,,\r\n"),
("one-empty-field", &[&["note"], &[""], &["x"]], "note\r\n\"\"\r\nx\r\n"),
("spaces", &[&["a", "b"], &[" x ", " y"]], "a,b\r\n x , y\r\n"),
("no-records", &[], ""),
("non-ascii", &[&["city"], &["Zürich"], &["東京"]], "city\r\nZürich\r\n東京\r\n"),
];
fn records(rows: &[&[&str]]) -> Vec<Vec<String>> {
rows.iter().map(|r| r.iter().map(|f| f.to_string()).collect()).collect()
}
#[test]
fn format_and_write() {
for (name, rows, want) in CASES {
let recs = records(rows);
assert_eq!(format_csv(&recs).unwrap(), *want, "{name}");
let path = std::env::temp_dir().join(format!("write-csv-{}-{name}.csv", std::process::id()));
write_csv(&path, &recs).unwrap();
let data = fs::read(&path).unwrap();
fs::remove_file(&path).unwrap();
assert_eq!(data, want.as_bytes(), "{name}");
}
}
#[test]
fn field_count() {
for (name, rows) in [("too-many-fields", &[&["a", "b"][..], &["1", "2", "3"]]), ("too-few-fields", &[&["a", "b"][..], &["1"]])] {
let recs = records(rows);
assert!(matches!(format_csv(&recs), Err(CsvError::FieldCount { record: 1, .. })), "{name}");
let path = std::env::temp_dir().join(format!("write-csv-{}-{name}.csv", std::process::id()));
assert!(matches!(write_csv(&path, &recs), Err(CsvError::FieldCount { .. })), "{name}");
assert!(!path.exists(), "{name}");
}
}
References
- 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
- The Python Standard Library, csv, csv.writer; Dialect.lineterminator; csv.QUOTE_MINIMAL; footnote 1
- Node.js documentation, File system, fs.writeFileSync(file, data[, options])
- Java SE 25 API, java.nio.file.Files, writeString(Path, CharSequence, OpenOption...)
- .NET API reference, File.WriteAllText, WriteAllText(String, String), Remarks
- The Rust Standard Library, std::fs::write, description
- cppreference.com, fopen, the file access mode flag "b"
- Go standard library, package encoding/csv, type Writer (UseCRLF, Flush, Error)
- The Python Standard Library, codecs, Encodings and Unicode, utf-8-sig
- OWASP Foundation, CSV Injection, Description; Mitigations
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag QY188M Edit this page History Report an error Markdown