#include #include #include #include "csv_parser.h" static void print_document(const csv_document_t *doc); 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; } csv_document_t *document = 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, &document); fclose(file); } else { /* Parse from stdin */ printf("CSV Parser - Enter CSV data (Ctrl+D to end):\n"); result = csv_parser_parse_file(parser, stdin, &document); } if (result == CSV_SUCCESS) { printf("Parsing completed successfully.\n"); print_document(document); csv_document_free(document); } 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_document(const csv_document_t *doc) { if (!doc) { printf("Document is NULL\n"); return; } printf("\nDocument summary:\n"); printf("- Records: %zu\n", doc->record_count); /* Print all records */ printf("\nRecords:\n"); csv_record_t *record = csv_document_get_first_record(doc); int record_num = 1; while (record) { printf("Record %d (%zu fields):\n", record_num++, record->field_count); csv_field_t *field = csv_record_get_first_field(record); int field_num = 1; while (field) { const char *content = csv_field_get_value(field); printf(" Field %d: '%s'\n", field_num++, content ? content : ""); field = csv_field_get_next(field); } record = csv_record_get_next(record); } } 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"); }