0

I've tried multiple stuff as reading new lines after checking if that columns is "General" but still does not work at all. It is an csv file and it would be lines with commas after each fgets and i need a specific column with it's data.

Here's my code:

char fi[1024];
while(!feof(CsvFile)){
    //Read
    fgets(fi, 1024, CsvFile);
    if(strstr(fi, "General") == 0){
        fscanf(CsvFile, "%[^\n]s", fi);
        printf("%s", fi);
    }
    fgetc(CsvFile);
}

It does not print what i want.

zdf
  • 4,382
  • 3
  • 18
  • 29
Yousef GH
  • 3
  • 4
  • 1
    "does not work" is not an adequate description of the problem. Please provide a [minimal verifiable example](https://stackoverflow.com/help/minimal-reproducible-example) as well as the exact file input, the expected output and actual output. – kaylum Dec 06 '19 at 09:58
  • 1
    [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – kaylum Dec 06 '19 at 09:59
  • 1
    Can you provide the `csv` file´s content and what you want from it in detailed explanation? – RobertS supports Monica Cellio Dec 06 '19 at 10:00

1 Answers1

0

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;
}
Community
  • 1
  • 1
zdf
  • 4,382
  • 3
  • 18
  • 29