Advertisement
rjcostales

csv.c

Aug 24th, 2021 (edited)
1,448
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.78 KB | None | 0 0
  1. // Quick 'n' Dirty CSV Parser
  2. // Jesse Costales
  3. // Aug 2021
  4. // rjcostales@gmail.com
  5. //
  6. // Use freely at own risk.
  7.  
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <ctype.h>
  11.  
  12. int main(int argc, char *argv[])
  13. {
  14.     char buffer[1024];
  15.     char *token, *quote, *comma;;
  16.  
  17.     while (fgets(buffer, 1024, stdin)) {
  18.         token = buffer;
  19.  
  20.         while (*token) {
  21.  
  22.             // remove whitespace
  23.             while (isspace(*token))
  24.                 token++;
  25.  
  26.             // check for quoted token
  27.             if (*token == '"') {
  28.                 quote = strchr(token + 1, '"');
  29.                 comma = strchr(quote, ',');
  30.             } else
  31.                 comma = strchr(token, ',');
  32.  
  33.             // find comma and print
  34.             if (comma) {
  35.                 *comma = '\0';
  36.                 printf("%s\t", token);
  37.                 token = comma + 1;
  38.             } else {
  39.                 printf("%s", token);
  40.                 break;
  41.             }
  42.         }
  43.     }
  44.  
  45.     return 0;
  46. }
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement