aboutsummaryrefslogtreecommitdiff
path: root/parse_csv.c
blob: 12e98f3575e90ab09fb44f349fcb43d7925ff5cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#include <istream>
#include <string>
#include <vector>
#include <stdexcept>
#include "parse_csv.h"
using namespace std;

/*************

Format defined:
  https://tools.ietf.org/html/rfc4180
See also:
  https://en.wikipedia.org/wiki/Comma-separated_values

We depart from the RFC by ignoring \r, so that lines can
end with either \r\n (dos style) or simply \n (unix style).

We check for malformed quoted fields and throw exceptions.

The last line of the input .csv file may or may not
contain a newline:
:; echo -en "xxx\n" | ./parse_csv_demo - | od -b -Anone
 170 170 170 012
:; echo -en "xxx" | ./parse_csv_demo - | od -b -Anone
 170 170 170 012

A line containing nothing but the newline has one field
with a zero-length datum:
:; echo -en "\n" | ./parse_csv_demo - | od -b -Anone
 012

A line containing no data /and/ no newline isn't a line
at all.  No line, no fields, no data:
:; echo -en "" | ./parse_csv_demo - | wc
      0       0       0

************/

string const Q("\"");

enum class CSVState {
    Start,
    UnquotedField,
    QuotedField,
    QuoteInQuote
};

// Read one row of .csv table.
// Return a zero-length vector if we encounter EoF
//   before seeing any data.
// Note that a table row can extend across multiple .csv file lines,
//   if there are embedded newlines.
//
// Within quoted fields, we accept commas, quotes, and newlines,
//   e.g "Hughie, ""Louie"", Dewey".
template <class datum = qstring>
vector<datum> readCSVRow(istream& input) {
  using namespace std;
  if (input.eof()) return vector<datum>(0);
  CSVState state = CSVState::Start;
  vector<datum> fields(0);
  char c;
  for (;;) {
    input.read(&c, 1);
    if (input.eof()) {
      if (state == CSVState::QuotedField)
        throw runtime_error("Unterminated quote in .csv file in field# "
                               + to_string(fields.size())
                    + "\n... namely <"
                    + Q + fields.back() + ">");
      break;
    }
    if (!input.good()) throw runtime_error("input error in .csv file");

// if we made it this far, the line contains at least one datum:
    if (fields.size() == 0) fields.push_back(datum());
    switch (state) {
      case CSVState::Start:
        switch (c) {
          case ',':     // zero-length field
            fields.push_back(datum());
            break;
          case '"':
            state = CSVState::QuotedField;
// This is no-op if the datum is not of type qstring:
            set_q(fields.back(), 1);
            break;
          case '\r':
            break;
          case '\n':
            goto EndRecord;
          default:
            state = CSVState::UnquotedField;
            fields.back().push_back(c);
            break;
        }
        break;
      case CSVState::UnquotedField:
        switch (c) {
          case ',': // start a new field:
            state = CSVState::Start;
            fields.push_back(datum());
            break;
          case '"': throw runtime_error
            ("Stray quote in .csv file in field# "
               + to_string(fields.size())
               + "\n... namely <"
               + fields.back() + Q + ">"
            );
            break;
          case '\r': break;
          case '\n': goto EndRecord;
          default:  fields.back().push_back(c);
            break;
        }
        break;
      case CSVState::QuotedField:
        switch (c) {
          case '"': state = CSVState::QuoteInQuote;
            break;
// Accept anything except quote here;
// that includes comma, \r, and \n.
          default:  fields.back().push_back(c);
            break;
        }
        break;
// Previous state saw a quote; we consider what follows:
      case CSVState::QuoteInQuote:
        switch (c) {
          case ',':     // comma after closing quote
            state = CSVState::Start;
            fields.push_back(datum());
            break;
          case '"':     // double ", map to plain "
            fields.back().push_back('"');
            state = CSVState::QuotedField;
            break;
          case '\r': break;
          case '\n': goto EndRecord;
          default:  throw runtime_error
              ("Extraneous verbiage in .csv file after quoted field# "
                    + to_string(fields.size())
                    + "\n... namely <"
                    + Q + fields.back() + Q
                    + string(1,c) +">");
            break;
        }
        break;
    }
  }
  EndRecord:;;;;
  return fields;
}

// Read entire CSV file.
// Within quoted fields, we accept commas, quotes, and newlines,
// e.g "Hughie, ""Louie"", Dewey".
template <class datum = qstring>
vector<vector<datum> > readCSV(istream &in) {
  using namespace std;
  vector<vector<datum> > table;
  datum row;
  while (!in.eof()) {
    auto fields = readCSVRow<datum>(in);
    if (fields.size() == 0) break;
    table.push_back(fields);
  }
  return table;
}

// Explicit instantiation for the <qstring> version.
// If you want some other version, you'll have to instantiate it.
template vector<qstring> readCSVRow<qstring>(istream& input);
template vector<vector<qstring> >readCSV<qstring>(istream &in);
// Apparently it's not necessary to mention get_q() here,
// but probably more portable to do it anyway:
////template int get_q<qstring>(qstring const&);

#if 1
// Explicit instantiation for the <string> version.
template vector<string> readCSVRow<string>(istream& input);
template vector<vector<string> >readCSV<string>(istream &in);
/////template int get_q<string>(string const&);
#endif