NoPaste

CSV parsing prototype

von Meillo

SNIPPET_TEXT:
  1. /*
  2. ** CSV parsing
  3. ** prototype, just hacked down quickly, to illustrate the general
  4. ** concept (... and for fun)
  5. */
  6.  
  7. #include <stdio.h>
  8.  
  9. int
  10. main(void)
  11. {
  12.         int c, fieldnum=1;
  13.         char *cp, buf[BUFSIZ];
  14.         enum state {Sep, Inquote, Noquote, Escape} state = Sep;
  15.  
  16.         cp = buf;
  17.         while ((c=getchar()) != EOF) {
  18.                 switch (c) {
  19.                 case '\n':
  20.                         if (state == Inquote) {
  21.                                 fprintf(stderr, "Open quotes at EOL\n");
  22.                                 continue;
  23.                         } else if (state == Escape) {
  24.                                 /* end of quote */
  25.                                 state = Sep;
  26.                         }
  27.                         *cp++ = '\0';
  28.                         printf("Field %02d: %s\n", fieldnum, buf);
  29.                         buf[0] = '\n';
  30.                         cp = buf;
  31.                         putchar('\n');
  32.                         fieldnum = 1;
  33.                         break;
  34.  
  35.                 case ',':
  36.                         if (state == Inquote) {
  37.                                 *cp++ = c;
  38.                                 continue;
  39.                         } else if (state == Escape) {
  40.                                 /* end of quotes */
  41.                                 state = Sep;
  42.                         }
  43.                         *cp++ = '\0';
  44.                         printf("Field %02d: %s\n", fieldnum, buf);
  45.                         buf[0] = '\n';
  46.                         cp = buf;
  47.                         fieldnum++;
  48.                         break;
  49.  
  50.                 case '"':
  51.                         if (state == Sep) {
  52.                                 state = Inquote;
  53.                         } else if (state == Inquote) {
  54.                                 state = Escape;
  55.                         } else if (state == Noquote) {
  56.                                 *cp++ = c;
  57.                         } else if (state == Escape) {
  58.                                 *cp++ = c;
  59.                                 state = Inquote;
  60.                         }
  61.                         break;
  62.  
  63.                 default:
  64.                         *cp++ = c;
  65.                         break;
  66.                 }
  67.         }
  68.  
  69.         return 0;
  70. }

Quellcode

Hier kannst du den Code kopieren und ihn in deinen bevorzugten Editor einfügen. PASTEBIN_DOWNLOAD_SNIPPET_EXPLAIN