Sergio923

ReadCSV.c

Nov 28th, 2020 (edited)
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.59 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. const char* getfield(char* line, int num)
  6. {
  7.     const char* tok;
  8.     for (tok = strtok(line, ";");
  9.             tok && *tok;
  10.             tok = strtok(NULL, ";\n"))
  11.     {
  12.         if (!--num)
  13.             return tok;
  14.     }
  15.     return NULL;
  16. }
  17.  
  18. int main()
  19. {
  20.     FILE* stream = fopen("test.csv", "r");
  21.  
  22.     char line[1024];
  23.     while (fgets(line, 1024, stream))
  24.     {
  25.         char* tmp = strdup(line);
  26.         printf("Field 3 would be %s\n", getfield(tmp,1));
  27.         // NOTE strtok clobbers tmp
  28.         free(tmp);
  29.     }
  30. }
Add Comment
Please, Sign In to add comment