I need to read from a csv file in C. The file contains of \'n\' number of lines
ID: 3743573 • Letter: I
Question
I need to read from a csv file in C. The file contains of 'n' number of lines which is unknown. The first integer in each line is a serial number from 1 to 'n' which is followed by 12 decimal numbers. The contents of csv file appears like :
1,0.4735838,0.2188502,0.3218017,0.3908641,0.8747335,0.8661728,0.7645371,0.7671346,0.607022,0.2362864,0.7524279,0.1373587
2,0.4587781,-0.6874146,0.0585485,0.0981094,0.7597714,0.3514413,0.3402567,1.009966,0.0289762,0.1513164,0.4348733,0.113073
3,0.128609,0.8866994,0.0304762,0.1793496,0.4125913,0.5130338,0.2015045,0.9654949,0.5079429,0.8854641,0.8281798,0.5769543
I want to store this in a 2d array. Please write the code with comments explaining how it can be handled. Thanks in advance.
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#define ARRAYSIZE(x) (sizeof(x)/sizeof(*(x)))
int main(void)
{
const char filename[] = "1.csv";
/*
* Open the file.
*/
FILE *file = fopen(filename, "r");
if ( file )
{
float array[3][26];
size_t i, j, k;
char buffer[BUFSIZ], *ptr;
/*
* Read each line from the file.
*/
for ( i = 0; fgets(buffer, sizeof buffer, file); ++i )
{
/*
* Parse the comma-separated values from each line into 'array'.
*/
for ( j = 0, ptr = buffer; j < ARRAYSIZE(*array); ++j, ++ptr )
{
array[i][j] = (int)strtol(ptr, &ptr, 10);
}
}
fclose(file);
/*
* Print the data in 'array'.
*/
for ( j = 0; j < i; ++j )
{
printf("array[%lu]: ", (long unsigned)j);
for ( k = 0; k < ARRAYSIZE(*array); ++k )
{
if (array[j][k]!=0)
printf("%f ", array[j][k]);
}
putchar(' ');
}
}
else /* fopen() returned NULL */
{
perror(filename);
}
return 0;
}