openPilotLog
readcsv.h
1 /*
2  *openPilotLog - A FOSS Pilot Logbook Application
3  *Copyright (C) 2020-2022 Felix Turowsky
4  *
5  *This program is free software: you can redistribute it and/or modify
6  *it under the terms of the GNU General Public License as published by
7  *the Free Software Foundation, either version 3 of the License, or
8  *(at your option) any later version.
9  *
10  *This program is distributed in the hope that it will be useful,
11  *but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  *GNU General Public License for more details.
14  *
15  *You should have received a copy of the GNU General Public License
16  *along with this program. If not, see <https://www.gnu.org/licenses/>.
17  */
18 #ifndef READCSV_H
19 #define READCSV_H
20 
21 #include<QtCore>
22 
23 namespace CSV {
24 
30 static inline QVector<QStringList> readCSVasColumns(const QString &filename)
31 {
32  QFile csvfile(filename);
33  csvfile.open(QIODevice::ReadOnly);
34  QTextStream stream(&csvfile);
35 
36  QVector<QStringList> values;
37 
38  //Read CSV headers and create QStringLists accordingly
39  QString line = stream.readLine();
40  auto items = line.split(",");
41  for (int i = 0; i < items.length(); i++) {
42  QStringList list;
43  list.append(items[i]);
44  values.append(list);
45  }
46  //Fill QStringLists with data
47  while (!stream.atEnd()) {
48  QString line = stream.readLine();
49  auto items = line.split(",");
50  for (int i = 0; i < values.length(); i++) {
51  values[i].append(items[i]);
52  }
53  }
54  return values;
55 }
56 
62 static inline QVector<QStringList> readCsvAsRows(const QString &file_name)
63 {
64  QFile csvfile(file_name);
65  csvfile.open(QIODevice::ReadOnly);
66  QTextStream stream(&csvfile);
67 
68  QVector<QStringList> csv_rows;
69 
70  // Read each line
71  while (!stream.atEnd()) {
72  const QString line = stream.readLine();
73  csv_rows.append(line.split(','));
74  }
75  return csv_rows;
76 }
77 
78 } // namespace CSV
79 
80 #endif // READCSV_H