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

3 Responses to “Reading CSV File Using C Program”

  1. Daniel Eidson on September 20th, 2008 7:17 pm

    Suppose your data were not three columns wide, but an unspecified number of columns wide. How would you go about retrieving the data in a similar format? For example, the first column would have the heading “Time of Arrival”, and then alternating columns would have the headings “Magnitude” and “Phase.”

    I tried to implement this using a “for” loop, but I started losing data (i.e., it did not start at the first entry, but at some random point in the middle of the csv file)

  2. Mark Marucot on November 18th, 2008 8:33 pm

    I apologize for not getting back to you. I’d been away because of work commitments. The code above is only applicable to fixed number of columns. To parse data in undefined number of columns you need to create a custom function that will extract column values by checking the position of the commas and quotations in a line.

  3. Dunxton on March 4th, 2009 12:18 am

    This code was really helpful for my need. Thanks.

Got something to say?