简体   繁体   中英

C - Checking for errors in file

I'm trying to get some ideas how to check for errors or mistypes in my data file. The errors are made by me, intentionally.

My file looks like this

Name HouseNr City Country number (how many sports) Sport1 Sport2 SportN

Carl Lincoln42 Houston USA 2 Basketball Football

while(fscanf(fData, "%s %s %s %s %d", (person + i)->name,
    (person + i)->adr.houseNr, (person + i)->adr.city, (huvi + i)->adr.country,
    &(sport + i)->sportCount) == 5)
{
    for (j = 0; j < (person + i)->sportCount; j++)
    {
        fscanf(fData, "%s", (person + i)->sportName[j]);
    }
    i++;
}

Now what I don't grasp is, how should I check for errors in that file.

Let's assume that number 's value is higher than that of the SportN .

This would mean that it scans other person's details as SportName

How should I tackle this? Change some code (please, some suggestions) or change the way I store my data?

As @SomeProgrammerDude mentioned in the comments , it is much better to read the file line by line and parse each line accordingly.

You can use the %[ format specifier to read lines from the file. This can be achieved by using %[^\\n] which tells *scanf to scan everything until a \\n (or EOF, whichever comes first). Of course, it doesn't scan in the \\n and as %[^\\n] will fail if the first character to be read is a \\n , you'll have to get rid of the newline after each line. This can be achieved by using a %*c right after the %[^\\n] . It tells *scanf to read and discard a character.

Now that you've read the line, its time to parse it. The sscanf function along with the help of the %n format specifier can be used for this.

char line[1000];
int i = 0;
while(fscanf(fData, "%[^\n]%*c", line) == 1)
{
    int offset;
    if(sscanf(line, "%s %s %s %s %d%n", (person + i)->name,
    (person + i)->adr.houseNr, (person + i)->adr.city, (huvi + i)->adr.country,
    &(sport + i)->sportCount, &offset) != 5)
    {
        fprintf(stderr, "Invalid line '%s'\n", line);
        i++;
        continue; /* Move on to next line */
    }
    bool valid = true;
    for(int j = 0; j < (sport + i)->sportCount; j++)
        if(sscanf(line + offset, "%s%n", (person + i)->sportName[j], &offset) != 1)
        {
            valid = false;
            break;
        }
    char dummy[100];
    if(sscanf(line + offset, "%s", dummy) == 1)
        valid = false;

    if(valid)
        printf("Good input for line '%s'\n", line);
    else
        fprintf(stderr, "Invalid number of items in '%s'\n", line);
    i++;
}

Untested Code ↑

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM