Skip to content

CSV Diff — C++ source

Diff two CSVs by a key column: rows added, removed and changed, with the differing columns named. Quoted cells with commas, quotes and newlines are handled. Runs locally with a shareable link.

This is the C++ implementation — the same logic the interactive tool runs, in a shareable, citable form.

// csv-diff — key-based row diff of two RFC-4180 CSVs. C++17 port (canonical
// TS: src/lib/csv-diff.ts; Go twin: cli/csv-diff). Mirrors the sibling
// ports: a hand-rolled RFC-4180 parser (quoted cells with embedded commas,
// quotes and newlines; CR dropped; a trailing field without a newline still
// completes its row) with blank single-cell rows dropped as trailing noise,
// strict per-side validation (empty CSV, duplicate columns, ragged rows,
// duplicate keys — the pinned error strings via std::runtime_error), then a
// key-based diff over the sorted key union: added/removed rows and changed
// rows whose differing column names come out sorted.
#include <algorithm>
#include <iostream>
#include <map>
#include <set>
#include <stdexcept>
#include <string>
#include <vector>

using Cells = std::vector<std::string>;
using Record = std::map<std::string, std::string>; // column name → cell, sorted names

struct RowDiff {
    std::string key, type;          // 'added' | 'removed' | 'changed'
    std::vector<std::string> columns; // differing names on 'changed', sorted
    Record before, after;           // left / right record when present
};

// RFC 4180 parser mirroring the TS loop: lenient quotes, CR dropped, a
// trailing field without a newline still completes its row.
std::vector<Cells> csv_to_rows(const std::string &csv)
{
    std::vector<Cells> rows;
    Cells row;
    std::string field;
    bool in_q = false;
    for (std::size_t i = 0; i < csv.size(); i++) {
        char ch = csv[i];
        if (in_q) {
            if (ch == '"') {
                if (i + 1 < csv.size() && csv[i + 1] == '"') { field += '"'; i++; }
                else in_q = false;
            } else field += ch;
        } else if (ch == '"') in_q = true;
        else if (ch == ',') { row.push_back(field); field.clear(); }
        else if (ch == '\n') { row.push_back(field); field.clear(); rows.push_back(row); row.clear(); }
        else if (ch != '\r') field += ch;
    }
    if (!field.empty() || !row.empty()) { row.push_back(field); rows.push_back(row); }
    return rows;
}

// Blank single-cell rows are trailing noise to a diff, not data.
std::vector<Cells> parse_csv(const std::string &text)
{
    std::vector<Cells> out;
    for (const auto &r : csv_to_rows(text))
        if (!(r.size() == 1 && r[0].empty())) out.push_back(r);
    return out;
}

// Strict per-side validation → (header, records keyed by column name);
// throws with the pinned strings (empty CSV, duplicate column, ragged row).
std::pair<Cells, std::vector<Record>> to_records(const std::vector<Cells> &rows, const std::string &label)
{
    if (rows.empty()) throw std::runtime_error(label + ": empty CSV");
    const Cells &header = rows[0];
    std::set<std::string> seen;
    for (const auto &name : header)
        if (!seen.insert(name).second) throw std::runtime_error(label + ": duplicate column \"" + name + "\"");
    std::vector<Record> records;
    for (std::size_t r = 1; r < rows.size(); r++) {
        if (rows[r].size() != header.size())
            throw std::runtime_error(label + ": row " + std::to_string(r + 1) + " has " +
                std::to_string(rows[r].size()) + " cells, expected " + std::to_string(header.size()));
        Record rec;
        for (std::size_t c = 0; c < header.size(); c++) rec[header[c]] = rows[r][c];
        records.push_back(rec);
    }
    return {header, records};
}

struct DiffResult { std::vector<RowDiff> rows; bool same = false; std::string error; };

// Diff two CSVs by key column (default: the first header column). Headers
// must match exactly; errors travel as strings, never exceptions.
DiffResult csv_diff(const std::string &leftRaw, const std::string &rightRaw, const std::string &keyColumn = "")
{
    auto trim = [](const std::string &s) {
        std::size_t a = s.find_first_not_of(" \t\n\r\f\v");
        if (a == std::string::npos) return std::string();
        return s.substr(a, s.find_last_not_of(" \t\n\r\f\v") - a + 1);
    };
    if (trim(leftRaw).empty() || trim(rightRaw).empty()) return {{}, false, "Both inputs are required"};
    try {
        auto [lheader, lrecs] = to_records(parse_csv(leftRaw), "Left");
        auto [rheader, rrecs] = to_records(parse_csv(rightRaw), "Right");
        const std::string key = keyColumn.empty() ? lheader[0] : keyColumn;
        if (std::find(lheader.begin(), lheader.end(), key) == lheader.end())
            return {{}, false, "Left: no key column \"" + key + "\""};
        if (std::find(rheader.begin(), rheader.end(), key) == rheader.end())
            return {{}, false, "Right: no key column \"" + key + "\""};
        if (lheader != rheader) {
            auto join = [](const Cells &h) {
                std::string s;
                for (std::size_t i = 0; i < h.size(); i++) s += (i ? ", " : "") + h[i];
                return s;
            };
            return {{}, false, "Headers differ: left [" + join(lheader) + "] vs right [" + join(rheader) + "]"};
        }
        auto index = [](const std::vector<Record> &recs, const std::string &key, const std::string &label) {
            std::map<std::string, Record> by;
            for (const auto &rec : recs) {
                if (by.count(rec.at(key))) throw std::runtime_error(label + ": duplicate key \"" + rec.at(key) + "\"");
                by[rec.at(key)] = rec;
            }
            return by;
        };
        const auto leftBy = index(lrecs, key, "Left");
        const auto rightBy = index(rrecs, key, "Right");
        std::set<std::string> keys; // sorted key union
        for (const auto &[k, v] : leftBy) { (void)v; keys.insert(k); }
        for (const auto &[k, v] : rightBy) { (void)v; keys.insert(k); }
        DiffResult res;
        for (const auto &k : keys) {
            auto l = leftBy.find(k);
            auto r = rightBy.find(k);
            if (l == leftBy.end()) res.rows.push_back({k, "added", {}, {}, r->second});
            else if (r == rightBy.end()) res.rows.push_back({k, "removed", {}, l->second, {}});
            else {
                RowDiff d{k, "changed", {}, l->second, r->second};
                for (const auto &[name, val] : l->second)
                    if (name != key && r->second.at(name) != val) d.columns.push_back(name);
                std::sort(d.columns.begin(), d.columns.end());
                if (d.columns.empty()) continue;
                res.rows.push_back(d);
            }
        }
        res.same = res.rows.empty();
        return res;
    } catch (const std::runtime_error &e) {
        return {{}, false, e.what()};
    }
}

int main()
{
    DiffResult r = csv_diff("id,name\n1,Ada\n2,Bob", "id,name\n1,Ada\n2,Robert\n3,New");
    for (const auto &d : r.rows) {
        std::cout << d.key << ' ' << d.type;
        if (d.type == "changed") std::cout << " (" << d.columns[0] << ": " << d.before.at(d.columns[0])
            << " -> " << d.after.at(d.columns[0]) << ')';
        else if (d.type == "added") std::cout << " (" << d.after.at("name") << ')';
        std::cout << '\n';
    }
    std::cout << "same: " << (r.same ? "true" : "false") << '\n'; // same: false
    std::cout << csv_diff("id,name\n1,Ada\n1,Bob", "id,name\n1,Ada").error << '\n'; // Left: duplicate key "1"
    return 0;
}

Also available in 12 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →