Harry
Harry

Reputation: 198

How to read a .csv file in C

I know that there are other questions on this topic but I still can't find the solution to the problem.

I'm trying to read a .csv file in C using the fscanf() function.

If I open the csv file with a text editor it looks like this:

578,2.2212e+05,223,0,243,0,0,0.09,0,0,0,3
633,2.2222e+05,223,0,243,0,0,-0.04,0,0,0,3
688,2.2232e+05,223,0,243,0,0,0.07,0,0,0,3
740,2.2242e+05,223,0,243,0,0,0.04,0,0,0,3
793,2.2252e+05,224,0,244,0,0.01,0.16,0,0,0,3
848,2.2262e+05,223,0,717,0.060985,0.02,0.08,0,0,0,4
902,2.2272e+05,223,0,721,0.084618,0.03,0.24,0,0,0,5
955,2.2282e+05,223,0,730,0.12825,0.05,0.34,0,0,0,4

I just reported the first few rows but it contains a lot more.

Then I used this code to read the file:

FILE* stream = fopen("./filelog.csv", "r");
if(stream == NULL) {      
       printf("\n file opening failed ");      
       return -1 ;   
} 
int values[8];
int count;
for(count = 0; count < 8; count++) {

    int u = fscanf(stream, "%i", &values[count]);
    printf("%i\n", values[count]);
}

The output I get is the following:

578
32697
0 
0
1
0
4199901
0

We can see that only the first value is read correctly. How could I read the whole file and store it into a matrix? I can't find any solution anywhere. Thank you so much for your replies in advance!

Upvotes: 0

Views: 1359

Answers (1)

unwind
unwind

Reputation: 399881

Your format string %i parses a single integer, but the next thing after the integer is a comma, and you're not parsing that. You should always check the return value, to make sure parsing succeeded, before using the value(s).

You need a format string that matches the actual content of the file, something like:

if (fscanf(stream, " %d,%f,%d,%d,%d,%d,%d,%f,%d,%d,%d,%d", ...) == 12)
{
}

in the code above the ... means "put pointers to 12 variables of the proper types, here". The space at the front of the format string is intended to help "consume" whitespace (like linefeeds) in the stream.

Upvotes: 7

Related Questions