csvvalid.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. csvvalid - determine if files are properly formed CSV files and display
  3. position of first offending byte if not
  4. */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <errno.h>
  9. #include <csv.h>
  10. int
  11. main (int argc, char *argv[])
  12. {
  13. FILE *fp;
  14. int i;
  15. struct csv_parser p;
  16. char buf[1024];
  17. size_t bytes_read;
  18. size_t pos;
  19. size_t retval;
  20. if (argc < 2) {
  21. fprintf(stderr, "Usage: csvvalid files\n");
  22. exit(EXIT_FAILURE);
  23. }
  24. if (csv_init(&p, CSV_STRICT) != 0) {
  25. fprintf(stderr, "Failed to initialize csv parser\n");
  26. exit(EXIT_FAILURE);
  27. }
  28. for (i = 1; i < argc; i++) {
  29. pos = 0;
  30. fp = fopen(argv[i], "rb");
  31. if (!fp) {
  32. fprintf(stderr, "Failed to open %s: %s, skipping\n", argv[i], strerror(errno));
  33. continue;
  34. }
  35. while ((bytes_read=fread(buf, 1, 1024, fp)) > 0) {
  36. if ((retval = csv_parse(&p, buf, bytes_read, NULL, NULL, NULL)) != bytes_read) {
  37. if (csv_error(&p) == CSV_EPARSE) {
  38. printf("%s: malformed at byte %lu\n", argv[i], (unsigned long)pos + retval + 1);
  39. goto end;
  40. } else {
  41. printf("Error while processing %s: %s\n", argv[i], csv_strerror(csv_error(&p)));
  42. goto end;
  43. }
  44. }
  45. pos += bytes_read;
  46. }
  47. printf("%s well-formed\n", argv[i]);
  48. end:
  49. fclose(fp);
  50. csv_fini(&p, NULL, NULL, NULL);
  51. pos = 0;
  52. }
  53. csv_free(&p);
  54. return EXIT_SUCCESS;
  55. }