Home > Blockchain >  Why fscanf in c reads csv files wrong?
Why fscanf in c reads csv files wrong?

Time:11-12

I am making a linked list of World Cup teams, when loading the teams I need to do a preload reading data from a csv file but reading 2-word countries makes it wrong

For example

Suppose that this is the csv file:

Arabia Saudita, Herve, Renard, Salman, C, 0, 1

First I read the country name, dt name, captain name, group and two numeric values that are part of the program, but the output is something like this:

Country:Arabia DT:Saudita Herve Renard Salman C 0 1 Captain: empty Group:Empty 

The expected output would be

Country: Arabia Saudita DtName:Herve DtSurname:Renard CaptainName:Salman Group: C

I tried to do it with a txt file but it is the same since it reads the spaces and the program fails or prints wrong

This is a part of the code that fails

    FILE *chargue = fopen("Precharge.csv", "r");
    
    while (!feof(charge)) {
        fscanf(charge, "%s\n", countryAux);
        chargecountry(&team, countryAux);
    
        fscanf(charge, "%s\n", nameDTAux);
        fscanf(charge, "%s\n", surnameDTAux);
        chargenameDT(&team, surnameDTAux, nameDTAux);
    
        chargeCapitan(&team, nameCapaux);
    
        fscanf(charge, "%c\n", &groupAux);
        chargegropu(&team, groupAux);
    
        fscanf(charge, "%d\n", &actualscoreaux);
        chargeactualscore(&team, actualscoreaux);
    
        fscanf(charge, "%d\n", &faseActualaux);
        chargeFase(&team, faseActualaux);
    
        insert(lis, team);
        forwards(lis);
    }

CodePudding user response:

Your format strings parse single words and do not stop at the , separator.

Parsing the csv file (or any file in general) with fscanf() is not recommended as it is very difficult to recover from errors and newlines are mostly indistinguishable from other space characters. Furthermore, it is incorrect to use while (!feof(charge)) to run this loop.

You can learn Why is “while( !feof(file) )” always wrong? and you should tell you teacher about this. It is a common mistake to use feof() for this pupose.

You should instead read one line at a time with fgets() and use %nnn[^,] conversion specifiers to parse the character fields (nnn being the maximum field length).

Here is an example:

#include <errno.h>
#include <stdio.h>
#include <string.h>

int main() {
    char buf[256];
    char countryAux[100];
    char nameDTAux[100];
    char surnameDTAux[100];
    char groupAux;
    int actualscoreaux, faseActualaux;
    ... // declare team, lis...

    FILE *chargue = fopen("Precharge.csv", "r");
    if (chargue == NULL) {
        fprintf(stderr, "cannot open %s: %s\n", "Precharge.csv",
                strerror(errno));
        return 1;
    }
    
    while (fgets(buf, sizeof buf, chargue)) {
        if (sscanf(buf, "           
  • Related