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  : source(source), fieldSeparator(fieldSeparator), userHeadingsProvided(headings), maxLineLength(maxLineLength),
51  headings(headings)
52  {
53  reset();
54  }
55 
62  void reset();
63 
67  bool next()
68  {
69  return readRow();
70  }
71 
75  unsigned count() const
76  {
77  return headings.count();
78  }
79 
85  const char* getValue(unsigned index)
86  {
87  return row[index];
88  }
89 
95  const char* getValue(const char* name)
96  {
97  return getValue(getColumn(name));
98  }
99 
105  int getColumn(const char* name)
106  {
107  return headings.indexOf(name);
108  }
109 
113  explicit operator bool() const
114  {
115  return bool(row);
116  }
117 
121  const CStringArray& getHeadings() const
122  {
123  return headings;
124  }
125 
129  const CStringArray& getRow() const
130  {
131  return row;
132  }
133 
134 private:
135  bool readRow();
136 
137  std::unique_ptr<IDataSourceStream> source;
138  char fieldSeparator;
139  bool userHeadingsProvided;
140  size_t maxLineLength;
141  CStringArray headings;
142  CStringArray row;
143 };
Class to manage a double null-terminated list of strings, such as "one\0two\0three\0".
Definition: CStringArray.h:22
int indexOf(const char *str, bool ignoreCase=true) const
Find the given string and return its index.
unsigned count() const
Get quantity of strings in array.
Class to parse a CSV file.
Definition: CsvReader.h:39
void reset()
Reset reader to start of CSV file.
const CStringArray & getHeadings() const
Get headings.
Definition: CsvReader.h:121
CsvReader(IDataSourceStream *source, char fieldSeparator=',', const CStringArray &headings=nullptr, size_t maxLineLength=2048)
Construct a CSV reader.
Definition: CsvReader.h:48
const CStringArray & getRow() const
Get current row.
Definition: CsvReader.h:129
const char * getValue(const char *name)
Get a value from the current row.
Definition: CsvReader.h:95
int getColumn(const char *name)
Get index of column given its name.
Definition: CsvReader.h:105
const char * getValue(unsigned index)
Get a value from the current row.
Definition: CsvReader.h:85
bool next()
Seek to next record.
Definition: CsvReader.h:67
unsigned count() const
Get number of columns.
Definition: CsvReader.h:75
Base class for read-only stream.
Definition: DataSourceStream.h:46