GCsv.cpp
19.2 KB
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
/***************************************************************************
* GCsv.cpp - Comma-separated values table class *
* ----------------------------------------------------------------------- *
* copyright (C) 2010-2018 by Juergen Knoedlseder *
* ----------------------------------------------------------------------- *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
***************************************************************************/
/**
* @file GCsv.cpp
* @brief Comma-separated values table class implementation
* @author Juergen Knoedlseder
*/
/* __ Includes ___________________________________________________________ */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <cstdio> // std::fopen, std::fgets, std::fclose, etc...
#include "GCsv.hpp"
#include "GTools.hpp"
#include "GFilename.hpp"
#include "GException.hpp"
/* __ Method name definitions ____________________________________________ */
#define G_ACCESS "GCsv::operator()(int&, int&)"
#define G_APPEND "GCsv::append(std::vector<std::string>&)"
#define G_LOAD "GCsv::load(GFilename&, std::string&)"
#define G_SAVE "GCsv::save(GFilename&, std::string&, bool&)"
/* __ Macros _____________________________________________________________ */
/* __ Coding definitions _________________________________________________ */
/* __ Debug definitions __________________________________________________ */
/*==========================================================================
= =
= Constructors/destructors =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Void constructor
***************************************************************************/
GCsv::GCsv(void)
{
// Initialise private members
init_members();
// Return
return;
}
/***********************************************************************//**
* @brief Table constructor
*
* @param[in] nrows Number of rows.
* @param[in] ncols Number of columns.
***************************************************************************/
GCsv::GCsv(const int& nrows, const int& ncols)
{
// Initialise private members
init_members();
// Allocate empty row
std::vector<std::string> row(ncols, "");
// Allocate table
m_data.assign(nrows, row);
// Set table dimensions
m_cols = ncols;
m_rows = nrows;
// Return
return;
}
/***********************************************************************//**
* @brief File constructor
*
* @param[in] filename Filename.
* @param[in] sep Column separator (default is whitespace).
***************************************************************************/
GCsv::GCsv(const GFilename& filename, const std::string& sep)
{
// Initialise private
init_members();
// Load CSV table
load(filename, sep);
// Return
return;
}
/***********************************************************************//**
* @brief Copy constructor
*
* @param[in] csv Comma-separated values table.
***************************************************************************/
GCsv::GCsv(const GCsv& csv)
{
// Initialise private
init_members();
// Copy members
copy_members(csv);
// Return
return;
}
/***********************************************************************//**
* @brief Destructor
***************************************************************************/
GCsv::~GCsv(void)
{
// Free members
free_members();
// Return
return;
}
/*==========================================================================
= =
= Operators =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Assignment operator
*
* @param[in] csv Comma-separated values table.
* @return Comma-separated values table.
***************************************************************************/
GCsv& GCsv::operator=(const GCsv& csv)
{
// Execute only if object is not identical
if (this != &csv) {
// Free members
free_members();
// Initialise private members for clean destruction
init_members();
// Copy members
copy_members(csv);
} // endif: object was not identical
// Return
return *this;
}
/***********************************************************************//**
* @brief Table element access operator
*
* @param[in] row Table row.
* @param[in] col Table column.
***************************************************************************/
std::string& GCsv::operator()(const int& row, const int& col)
{
// Perform range check
#if defined(G_RANGE_CHECK)
if (row < 0 || row >= m_rows || col < 0 || col >= m_cols) {
throw GException::out_of_range(G_ACCESS, row, col, m_rows-1, m_cols-1);
}
#endif
// Return element
return m_data[row][col];
}
/***********************************************************************//**
* @brief Table element access operator (const version)
*
* @param[in] row Table row.
* @param[in] col Table column.
***************************************************************************/
const std::string& GCsv::operator()(const int& row, const int& col) const
{
// Perform range check
#if defined(G_RANGE_CHECK)
if (row < 0 || row >= m_rows || col < 0 || col >= m_cols) {
throw GException::out_of_range(G_ACCESS, row, col, m_rows, m_cols);
}
#endif
// Return element
return m_data[row][col];
}
/*==========================================================================
= =
= Public methods =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Clear CSV table
*
* This method properly resets the object to an initial state.
***************************************************************************/
void GCsv::clear(void)
{
// Free class members
free_members();
// Initialise members
init_members();
// Return
return;
}
/***********************************************************************//**
* @brief Clone CSV table
*
* @return Pointer to deep copy of CSV table.
**************************************************************************/
GCsv* GCsv::clone(void) const
{
return new GCsv(*this);
}
/***********************************************************************//**
* @brief Append list of strings
*
* @param[in] list List of strings.
*
* @exception GException::invalid_argument
* Invalid number of elements in list.
*
* Appends a list of strings to the CSV table. If the table is empty, the
* number of elements in the list will determine the number of columns of
* the table. If a table exists already, the method will throw an exception
* if the number of elements in the list does not correspond to the number
* of table columns.
***************************************************************************/
void GCsv::append(const std::vector<std::string>& list)
{
// If we have already rows then check columns size ...
if (m_rows > 0) {
if (m_cols != list.size()) {
std::string msg = "Invalid attempt to append "+
gammalib::str(list.size())+" elements to a CSV "
"table with "+gammalib::str(m_cols)+" columns.";
throw GException::invalid_argument(G_APPEND, msg);
}
}
// ... otherwise store the number of columns
else {
m_cols = list.size();
}
// Append
m_data.push_back(list);
// Increment number of rows
m_rows++;
// Return
return;
}
/***********************************************************************//**
* @brief Get string value
*
* @param[in] row Table row.
* @param[in] col Table column.
*
* Returns value of specified row and column as string.
***************************************************************************/
std::string GCsv::string(const int& row, const int& col) const
{
// Return value
return (*this)(row, col);
}
/***********************************************************************//**
* @brief Get double precision value
*
* @param[in] row Table row.
* @param[in] col Table column.
*
* Returns value of specified row and column as double precision.
***************************************************************************/
double GCsv::real(const int& row, const int& col) const
{
// Convert element into double
double value = gammalib::todouble((*this)(row, col));
// Return value
return value;
}
/***********************************************************************//**
* @brief Get integer value
*
* @param[in] row Table row.
* @param[in] col Table column.
*
* Returns value of specified row and column as integer.
***************************************************************************/
int GCsv::integer(const int& row, const int& col) const
{
// Convert element into int
int value = gammalib::toint((*this)(row, col));
// Return value
return value;
}
/***********************************************************************//**
* @brief Get string value
*
* @param[in] row Table row.
* @param[in] col Table column.
* @param[in] value String value.
*
* Set value of specified row and column as string.
***************************************************************************/
void GCsv::string(const int& row, const int& col, const std::string& value)
{
// Set value
(*this)(row, col) = value;
// Return
return;
}
/***********************************************************************//**
* @brief Get double precision value
*
* @param[in] row Table row.
* @param[in] col Table column.
* @param[in] value Double precision floating point value.
*
* Set value of specified row and column as double precision floating point.
***************************************************************************/
void GCsv::real(const int& row, const int& col, const double& value)
{
// Set value
(*this)(row, col) = gammalib::str(value, m_precision);
// Return
return;
}
/***********************************************************************//**
* @brief Get integer value
*
* @param[in] row Table row.
* @param[in] col Table column.
* @param[in] value Integer value.
*
* Set value of specified row and column as integer.
***************************************************************************/
void GCsv::integer(const int& row, const int& col, const int& value)
{
// Set value
(*this)(row, col) = gammalib::str(value);
// Return
return;
}
/***********************************************************************//**
* @brief Load CSV table
*
* @param[in] filename Filename.
* @param[in] sep Column separator (default is whitespace).
*
* @exception GException::file_not_found
* CSV table file not found.
* @exception GException::csv_bad_columns
* Inconsistent columns encountered in CSV table file.
*
* Load CSV table from ASCII file. Any environment variable present in the
* filename will be expanded.
**************************************************************************/
void GCsv::load(const GFilename& filename, const std::string& sep)
{
// Clear instance
clear();
// Allocate line buffer
const int n = 10000;
char line[n];
// Expand environment variables
std::string fname = gammalib::expand_env(filename.url());
// Open CSV table (read-only)
FILE* fptr = std::fopen(fname.c_str(), "r");
if (fptr == NULL) {
throw GException::file_not_found(G_LOAD, fname);
}
// Read lines
int iline = 0;
while (std::fgets(line, n, fptr) != NULL) {
// Increment line counter
iline++;
// Get line with leading and trailing whitespace removed
std::string sline =
gammalib::strip_chars(gammalib::strip_whitespace(std::string(line)),"\n");
// Skip empty lines
if (sline.length() == 0) {
continue;
}
// Skip lines starting with a hash as those are comment lines
if (sline[0] == '#') {
continue;
}
// Split line in elements
std::vector<std::string> elements = gammalib::split(sline, sep);
for (int i = 0; i < elements.size(); ++i) {
elements[i] = gammalib::strip_whitespace(elements[i]);
}
// If this is the first valid line then simply store the elements
if (m_data.empty()) {
m_data.push_back(elements);
m_cols = elements.size();
}
// ... otherwise check table consistency and add elements
else {
// Check table consistency
if (m_cols != elements.size()) {
throw GException::csv_bad_columns(G_LOAD, fname,
iline, m_cols, elements.size());
}
// Append elements
m_data.push_back(elements);
}
// Increment number of rows
m_rows++;
} // endwhile: looped over lines
// Close file
std::fclose(fptr);
// Return
return;
}
/***********************************************************************//**
* @brief Save CSV table
*
* @param[in] filename Filename.
* @param[in] sep Column separator (default: whitespace).
* @param[in] clobber Overwrite existing file? (default: false).
*
* @exception GException::invalid_value
* Attempt to overwrite existing file.
* @exception GException::file_error
* Unable to create file.
*
* Save CSV table into ASCII file.
**************************************************************************/
void GCsv::save(const GFilename& filename,
const std::string& sep,
const bool& clobber) const
{
// Throw exception if file exists but clobber flag is false
if (!clobber && filename.exists()) {
std::string msg = "File \""+filename+"\" exists already but "
"the clobber flag is set to \"false\". Set the "
"clobber flag to true to overwrite the existing "
"file or specify another file name.";
throw GException::invalid_value(G_SAVE, msg);
}
// Open CSV table (write-only)
FILE* fptr = std::fopen(filename.url().c_str(), "w");
if (fptr == NULL) {
std::string msg = "Unable to create file \""+filename+"\".";
throw GException::file_error(G_SAVE, msg);
}
// Loop over the rows
for (int row = 0; row < m_rows; ++row) {
// Write columns
for (int col = 0; col < m_cols; ++col) {
std::fputs(m_data[row][col].c_str(), fptr);
if (col < m_cols-1) {
std::fputs(sep.c_str(), fptr);
}
}
// Write linebreak
std::fputs("\n", fptr);
} // endfor: looped over rows
// Close file
std::fclose(fptr);
// Return
return;
}
/***********************************************************************//**
* @brief Print column separated values information
*
* @param[in] chatter Chattiness (defaults to NORMAL).
* @return String containing column separated values information.
***************************************************************************/
std::string GCsv::print(const GChatter& chatter) const
{
// Initialise result string
std::string result;
// Continue only if chatter is not silent
if (chatter != SILENT) {
// Append header
result.append("=== GCsv ===");
// Append information
result.append("\n"+gammalib::parformat("Number of columns"));
result.append(gammalib::str(m_cols));
result.append("\n"+gammalib::parformat("Number of rows"));
result.append(gammalib::str(m_rows));
result.append("\n"+gammalib::parformat("Floating point precision"));
if (m_precision == 0) {
result.append("default");
}
else {
result.append(gammalib::str(m_precision));
}
} // endif: chatter was not silent
// Return result
return result;
}
/*==========================================================================
= =
= Private methods =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Initialise class members
***************************************************************************/
void GCsv::init_members(void)
{
// Initialise members
m_cols = 0;
m_rows = 0;
m_data.clear();
m_precision = 0;
// Return
return;
}
/***********************************************************************//**
* @brief Copy class members
*
* @param[in] csv Comma-separated values table.
***************************************************************************/
void GCsv::copy_members(const GCsv& csv)
{
// Copy members
m_cols = csv.m_cols;
m_rows = csv.m_rows;
m_data = csv.m_data;
m_precision = csv.m_precision;
// Return
return;
}
/***********************************************************************//**
* @brief Delete class members
***************************************************************************/
void GCsv::free_members(void)
{
// Return
return;
}