Vince's CSV Parser
csv_utility.cpp
1 #include <sstream>
2 #include <vector>
3 
4 #include "csv_utility.hpp"
5 
6 namespace csv {
15  std::stringstream stream(in.data());
16  return CSVReader(stream, format);
17  }
18 
24  CSVFormat format;
25  format.header_row(-1);
26 
27  return parse(in, format);
28  }
29 
37  CSV_INLINE CSVReader operator ""_csv(const char* in, size_t n) {
38  return parse(csv::string_view(in, n));
39  }
40 
42  CSV_INLINE CSVReader operator ""_csv_no_header(const char* in, size_t n) {
43  return parse_no_header(csv::string_view(in, n));
44  }
45 
54  csv::string_view filename,
55  csv::string_view col_name,
56  const CSVFormat& format) {
57  CSVReader reader(filename, format);
58  return reader.index_of(col_name);
59  }
60 
64  CSV_INLINE CSVFileInfo get_file_info(const std::string& filename) {
65  CSVReader reader(filename);
66  CSVFormat format = reader.get_format();
67  for (auto it = reader.begin(); it != reader.end(); ++it);
68 
69  CSVFileInfo info = {
70  filename,
71  reader.get_col_names(),
72  format.get_delim(),
73  reader.n_rows(),
74  reader.get_col_names().size()
75  };
76 
77  return info;
78  }
79 }
Stores information about how to parse a CSV file.
Definition: csv_format.hpp:36
CSVFormat & header_row(int row)
Sets the header row.
Definition: csv_format.cpp:42
Main class for parsing CSVs from files and in-memory sources.
Definition: csv_reader.hpp:57
CSVFormat get_format() const
Return the format of the original raw CSV.
Definition: csv_reader.cpp:174
int index_of(csv::string_view col_name) const
Return the index of the column name if found or csv::CSV_NOT_FOUND otherwise.
Definition: csv_reader.cpp:198
HEDLEY_CONST iterator end() const noexcept
A placeholder for the imaginary past the end row in a CSV.
CONSTEXPR size_t n_rows() const noexcept
Retrieves the number of rows that have been read so far.
Definition: csv_reader.hpp:171
std::vector< std::string > get_col_names() const
Return the CSV's column names as a vector of strings.
Definition: csv_reader.cpp:187
iterator begin()
Return an iterator to the first row in the reader.
#define CSV_INLINE
Helper macro which should be #defined as "inline" in the single header version.
Definition: common.hpp:26
The all encompassing namespace.
int get_col_pos(csv::string_view filename, csv::string_view col_name, const CSVFormat &format)
Find the position of a column in a CSV file or CSV_NOT_FOUND otherwise.
Definition: csv_utility.cpp:53
CSVFileInfo get_file_info(const std::string &filename)
Get basic information about a CSV file.
Definition: csv_utility.cpp:64
CSVReader parse(csv::string_view in, CSVFormat format)
Shorthand function for parsing an in-memory CSV string.
Definition: csv_utility.cpp:14
CSVReader parse_no_header(csv::string_view in)
Parses a CSV string with no headers.
Definition: csv_utility.cpp:23
nonstd::string_view string_view
The string_view class used by this library.
Definition: common.hpp:75
Returned by get_file_info()
Definition: csv_utility.hpp:13