4 #include "csv_parser.h"
6 static void print_records(const vector *records);
7 static void print_usage(const char *program_name);
9 int main(int argc, char *argv[])
11 csv_parser_t *parser = csv_parser_create();
13 fprintf(stderr, "Error: Failed to create CSV parser\n");
17 vector *records = NULL;
19 char *filename = NULL;
21 /* Parse command line arguments */
22 for (int i = 1; i < argc; i++) {
23 if (strcmp(argv[i], "--help") == 0) {
25 csv_parser_destroy(parser);
27 } else if (argv[i][0] != '-') {
30 fprintf(stderr, "Error: Unknown option '%s'\n", argv[i]);
32 csv_parser_destroy(parser);
38 /* Parse file argument */
39 FILE *file = fopen(filename, "r");
41 fprintf(stderr, "Error: Cannot open file '%s'\n", filename);
42 csv_parser_destroy(parser);
46 printf("Parsing CSV file: %s\n", filename);
47 result = csv_parser_parse_file(parser, file, &records);
50 /* Parse from stdin */
51 printf("CSV Parser - Enter CSV data (Ctrl+D to end):\n");
52 result = csv_parser_parse_file(parser, stdin, &records);
55 if (result == CSV_SUCCESS) {
56 printf("Parsing completed successfully.\n");
57 print_records(records);
60 printf("Parsing failed: %s\n", csv_error_string(result));
62 csv_error_info_t error_info = csv_parser_get_error_info(parser);
63 if (error_info.has_location) {
64 printf("Error details: %s (line %d, column %d)\n",
65 error_info.message, error_info.line, error_info.column);
67 printf("Error details: %s\n", error_info.message);
71 csv_parser_destroy(parser);
72 return result == CSV_SUCCESS ? 0 : 1;
75 static void print_records(const vector *records)
78 printf("Records vector is NULL\n");
82 printf("\nDocument summary:\n");
83 printf("- Records: %zu\n", v_length(records));
85 /* Print all records */
86 printf("\nRecords:\n");
87 for (size_t i = 0; i < v_length(records); i++) {
88 csv_record_t *record = v_at(records, i);
90 printf("Record %zu (%zu fields):\n", i + 1, v_length(record->fields));
92 for (size_t j = 0; j < v_length(record->fields); j++) {
93 const char *content = v_at(record->fields, j);
94 printf(" Field %zu: '%s'\n", j + 1, content ? content : "");
100 static void print_usage(const char *program_name)
102 printf("Usage: %s [filename]\n", program_name);
103 printf("Options:\n");
104 printf(" --help Show this help message\n");
106 printf(" If filename is provided, parse that file\n");
107 printf(" Otherwise, read from standard input\n");