/* ** CSV parsing ** prototype, just hacked down quickly, to illustrate the general ** concept (... and for fun) */ #include int main(void) { int c, fieldnum=1; char *cp, buf[BUFSIZ]; enum state {Sep, Inquote, Noquote, Escape} state = Sep; cp = buf; while ((c=getchar()) != EOF) { switch (c) { case '\n': if (state == Inquote) { fprintf(stderr, "Open quotes at EOL\n"); continue; } else if (state == Escape) { /* end of quote */ state = Sep; } *cp++ = '\0'; printf("Field %02d: %s\n", fieldnum, buf); buf[0] = '\n'; cp = buf; putchar('\n'); fieldnum = 1; break; case ',': if (state == Inquote) { *cp++ = c; continue; } else if (state == Escape) { /* end of quotes */ state = Sep; } *cp++ = '\0'; printf("Field %02d: %s\n", fieldnum, buf); buf[0] = '\n'; cp = buf; fieldnum++; break; case '"': if (state == Sep) { state = Inquote; } else if (state == Inquote) { state = Escape; } else if (state == Noquote) { *cp++ = c; } else if (state == Escape) { *cp++ = c; state = Inquote; } break; default: *cp++ = c; break; } } return 0; }