csvfix.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. csvfix - reads (possibly malformed) CSV data from input file
  3. and writes properly formed CSV to output file
  4. */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <errno.h>
  9. #include <csv.h>
  10. void cb1 (void *s, size_t i, void *outfile) {
  11. csv_fwrite((FILE *)outfile, s, i);
  12. fputc(',',(FILE *)outfile);
  13. }
  14. void cb2 (int c, void *outfile) {
  15. fseek((FILE *)outfile, -1, SEEK_CUR);
  16. fputc('\n', (FILE *)outfile);
  17. }
  18. int main (int argc, char *argv[]) {
  19. char buf[1024];
  20. size_t i;
  21. struct csv_parser p;
  22. FILE *infile, *outfile;
  23. csv_init(&p, 0);
  24. if (argc != 3) {
  25. fprintf(stderr, "Usage: csv_fix infile outfile\n");
  26. return EXIT_FAILURE;
  27. }
  28. if (!strcmp(argv[1], argv[2])) {
  29. fprintf(stderr, "Input file and output file must not be the same!\n");
  30. exit(EXIT_FAILURE);
  31. }
  32. infile = fopen(argv[1], "rb");
  33. if (infile == NULL) {
  34. fprintf(stderr, "Failed to open file %s: %s\n", argv[1], strerror(errno));
  35. exit(EXIT_FAILURE);
  36. }
  37. outfile = fopen(argv[2], "wb");
  38. if (outfile == NULL) {
  39. fprintf(stderr, "Failed to open file %s: %s\n", argv[2], strerror(errno));
  40. fclose(infile);
  41. exit(EXIT_FAILURE);
  42. }
  43. while ((i=fread(buf, 1, 1024, infile)) > 0) {
  44. if (csv_parse(&p, buf, i, cb1, cb2, outfile) != i) {
  45. fprintf(stderr, "Error parsing file: %s\n", csv_strerror(csv_error(&p)));
  46. fclose(infile);
  47. fclose(outfile);
  48. remove(argv[2]);
  49. exit(EXIT_FAILURE);
  50. }
  51. }
  52. csv_fini(&p, cb1, cb2, outfile);
  53. csv_free(&p);
  54. if (ferror(infile)) {
  55. fprintf(stderr, "Error reading from input file");
  56. fclose(infile);
  57. fclose(outfile);
  58. remove(argv[2]);
  59. exit(EXIT_FAILURE);
  60. }
  61. fclose(infile);
  62. fclose(outfile);
  63. return EXIT_SUCCESS;
  64. }