CsvReader.h
Go to the documentation of this file.
1 /****
2  * Sming Framework Project - Open Source framework for high efficiency native ESP8266 development.
3  * Created 2015 by Skurydin Alexey
4  * http://github.com/SmingHub/Sming
5  * All files of the Sming Core are provided under the LGPL v3 license.
6  *
7  * CsvReader.h
8  *
9  * @author: 2021 - Mikee47 <mike@sillyhouse.net>
10  *
11  ****/
12 
13 #pragma once
14 
16 #include "CStringArray.h"
17 #include <memory>
18 
38 class CsvReader
39 {
40 public:
48  CsvReader(IDataSourceStream* source, char fieldSeparator = ',', const CStringArray& headings = nullptr,
49  size_t maxLineLength = 2048)
50  : fieldSeparator(fieldSeparator), userHeadingsProvided(headings), maxLineLength(maxLineLength),
51  headings(headings)
52  {
53  this->source.reset(source);
54  reset();
55  }
56 
63  void reset();
64 
68  bool next()
69  {
70  return readRow();
71  }
72 
76  unsigned count() const
77  {
78  return headings.count();
79  }
80 
86  const char* getValue(unsigned index)
87  {
88  return row[index];
89  }
90 
96  const char* getValue(const char* name)
97  {
98  return getValue(getColumn(name));
99  }
100 
106  int getColumn(const char* name)
107  {
108  return headings.indexOf(name);
109  }
110 
114  explicit operator bool() const
115  {
116  return bool(row);
117  }
118 
122  const CStringArray& getHeadings() const
123  {
124  return headings;
125  }
126 
130  const CStringArray& getRow() const
131  {
132  return row;
133  }
134 
135 private:
136  bool readRow();
137 
138  std::unique_ptr<IDataSourceStream> source;
139  char fieldSeparator;
140  bool userHeadingsProvided;
141  size_t maxLineLength;
142  CStringArray headings;
143  CStringArray row;
144 };
Base class for read-only stream.
Definition: DataSourceStream.h:45
CsvReader(IDataSourceStream *source, char fieldSeparator=',', const CStringArray &headings=nullptr, size_t maxLineLength=2048)
Construct a CSV reader.
Definition: CsvReader.h:58
Class to parse a CSV file.
Definition: CsvReader.h:38
bool next()
Seek to next record.
Definition: CsvReader.h:78
void reset()
Reset reader to start of CSV file.
int getColumn(const char *name)
Get index of column given its name.
Definition: CsvReader.h:116
const CStringArray & getHeadings() const
Get headings.
Definition: CsvReader.h:132
unsigned count() const
Get quantity of strings in array.
const CStringArray & getRow() const
Get current row.
Definition: CsvReader.h:140
const char * getValue(unsigned index)
Get a value from the current row.
Definition: CsvReader.h:96
unsigned count() const
Get number of columns.
Definition: CsvReader.h:86
Class to manage a double null-terminated list of strings, such as "one\0two\0three\0".
Definition: CStringArray.h:21
int indexOf(const char *str, bool ignoreCase=true) const
Find the given string and return its index.