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:
-
1111,1414,1000
-
1112,1010, 1001
-
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.
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <string.h>
-
-
int main(int argc, char* argv[])
-
{
-
if (argc <2)
-
{
-
fprintf(stderr,"Usage: %s csv_file\n",argv[0]);
-
return(1);
-
}
-
-
FILE *f = fopen(argv[1], "rt");
-
char Line[256];
-
unsigned int AllocSize = 0, Size = 0, n;
-
char *L_text;
-
-
while(fgets(Line, sizeof(Line), f))
-
{
-
-
printf("Item = %s \n",strtok(Line, ", "));
-
printf("Class = %s \n",strtok(NULL, ", "));
-
printf("Supplier = %s \n",strtok(NULL, ", "));
-
-
}
-
return(0);
-
}






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)
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.
This code was really helpful for my need. Thanks.