#include #include #include #include "csv_parser.h" static void print_records(const vector *records); static void print_usage(const char *program_name); int main(int argc, char *argv[]) { csv_parser_t *parser = csv_parser_create(); if (!parser) { fprintf(stderr, "Error: Failed to create CSV parser\n"); return 1; } vector *records = NULL; csv_error_t result; char *filename = NULL; /* Parse command line arguments */ for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "--help") == 0) { print_usage(argv[0]); csv_parser_destroy(parser); return 0; } else if (argv[i][0] != '-') { filename = argv[i]; } else { fprintf(stderr, "Error: Unknown option '%s'\n", argv[i]); print_usage(argv[0]); csv_parser_destroy(parser); return 1; } } if (filename) { /* Parse file argument */ FILE *file = fopen(filename, "r"); if (!file) { fprintf(stderr, "Error: Cannot open file '%s'\n", filename); csv_parser_destroy(parser); return 1; } printf("Parsing CSV file: %s\n", filename); result = csv_parser_parse_file(parser, file, &records); fclose(file); } else { /* Parse from stdin */ printf("CSV Parser - Enter CSV data (Ctrl+D to end):\n"); result = csv_parser_parse_file(parser, stdin, &records); } if (result == CSV_SUCCESS) { printf("Parsing completed successfully.\n"); print_records(records); v_free(records); } else { printf("Parsing failed: %s\n", csv_error_string(result)); csv_error_info_t error_info = csv_parser_get_error_info(parser); if (error_info.has_location) { printf("Error details: %s (line %d, column %d)\n", error_info.message, error_info.line, error_info.column); } else { printf("Error details: %s\n", error_info.message); } } csv_parser_destroy(parser); return result == CSV_SUCCESS ? 0 : 1; } static void print_records(const vector *records) { if (!records) { printf("Records vector is NULL\n"); return; } printf("\nDocument summary:\n"); printf("- Records: %zu\n", v_length(records)); /* Print all records */ printf("\nRecords:\n"); for (size_t i = 0; i < v_length(records); i++) { csv_record_t *record = v_at(records, i); if (record) { printf("Record %zu (%zu fields):\n", i + 1, v_length(record->fields)); for (size_t j = 0; j < v_length(record->fields); j++) { const char *content = v_at(record->fields, j); printf(" Field %zu: '%s'\n", j + 1, content ? content : ""); } } } } static void print_usage(const char *program_name) { printf("Usage: %s [filename]\n", program_name); printf("Options:\n"); printf(" --help Show this help message\n"); printf("\n"); printf(" If filename is provided, parse that file\n"); printf(" Otherwise, read from standard input\n"); }