Reading CSV File Using C Program

June 2, 2008 · Print This Article

Since I'm on an integration project, I'm mostly dealing with transferring of data from two or more systems whether it's from the legacy system or newly implemented system. Most of the type of data movement is sending CSV files to and from the different system. Here is a simple tutorial on how to read CSV. The CSV file contains the following:

CODE:
  1. 1111,1414,1000
  2. 1112,1010, 1001
  3. 1113,1112,1002

The fields are Item Number, Class Number and Supplier Number.

The example below is the simple code of reading CSV file in C.

CODE:
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int main(int argc, char* argv[])
  6. {
  7.    if (argc <2)
  8.    {
  9.       fprintf(stderr,"Usage: %s csv_file\n",argv[0]);
  10.       return(1);
  11.    }
  12.  
  13.     FILE *f = fopen(argv[1], "rt");
  14.     char Line[256];
  15.     unsigned int AllocSize = 0, Size = 0, n;
  16.     char *L_text;
  17.  
  18.     while(fgets(Line, sizeof(Line), f))
  19.     {
  20.  
  21.       printf("Item = %s \n",strtok(Line, ", "));
  22.       printf("Class = %s \n",strtok(NULL, ", "));
  23.       printf("Supplier = %s \n",strtok(NULL, ", "));
  24.  
  25.     }
  26.    return(0);
  27. }

Related Posts

Comments

Got something to say?