-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv_to_tsv_cpp.cpp
More file actions
83 lines (66 loc) · 1.71 KB
/
csv_to_tsv_cpp.cpp
File metadata and controls
83 lines (66 loc) · 1.71 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
#include <cstdio>
#include <iostream>
#include "ksv.hpp"
int main(int argc, char *argv[])
{
if (argc < 2) {
std::cerr << "No input sheet" << std::endl;
return 1;
}
FILE *fp = NULL;
KSV *ksv = NULL;
std::string field;
char *path = argv[1];
/* Open a CSV sheet. */
fp = fopen(path, "r");
if (!fp) {
std::cerr << "Unable to read file" << std::endl;
return 1;
}
/* Create a ksv object. */
try {
ksv = new KSV();
}
catch (std::exception &ex) {
goto ERROR_MAIN;
}
/* Load the header row of the sheet. */
if (!ksv->load_header(fp)) {
std::cerr << "Failed to load sheet header" << std::endl;
goto ERROR_MAIN;
}
/* Iterate over the header(s) of the header row. */
field = ksv->next_header();
while (!field.empty()) {
std::cout << field << "\t";
field = ksv->next_header();
}
std::cout << "\b" << std::endl;
/* Iterate over the sheet. */
while (!feof(fp)) {
/* Load one row from the sheet. */
if (!ksv->load_record(fp)) {
std::cerr << "Failed to load a sheet record" << std::endl;
goto ERROR_MAIN;
}
/* Re-init the state of the ksv object. */
ksv->start();
/* Iterate over the cell(s) of the row. */
field = ksv->next_data_by_row();
while (!field.empty()) {
std::cout << field << "\t";
field = ksv->next_data_by_row();
}
std::cout << "\b" << std::endl;
}
/* Release system resources. */
delete ksv;
fclose(fp);
return 0;
ERROR_MAIN:
if (ksv)
delete ksv;
if (fp)
fclose(fp);
return 1;
}