Reading a CSV file is much more complicated than you assumed (see https://www.rfc-editor.org/rfc/rfc4180). You must take all kind of rules into account. For instance, if a cell contains a comma, the content must be surrounded by "
.
However, you can implement a simplified version which assumes:
- a CSV file is made of lines;
- a line is MAX_LINE characters, at most;
- a line is made of cells;
- a cell ends with comma or new-line;
- a cell contains anything but comma or new-line.
The code below reads one line at a time and then uses strtok
to split the line into cells.
Welcome to SO and good luck!
#include <stdio.h>
#include <string.h>
#define MAX_LINE 1024
int main( int argc, char* argv[] )
{
//
FILE* fp = fopen( "c:\\temp\\so.txt", "r" );
if ( !fp )
{
printf( "could not open file" );
return -1;
}
//
char line[ MAX_LINE + 1 ];
while ( fgets( line, sizeof( line ) / sizeof( *line ), fp ) ) // get a line
{
int col_idx = 0;
const char* sep = "\r\n,"; // cells are separated by a comma or a new line
char* cell = strtok( line, sep ); // find first cell
while ( cell )
{
// your processing code goes here
cell = strtok( NULL, sep ); // next cell
col_idx++;
}
}
return 0;
}