perlponderer
perlponderer

Reputation: 43

fscanf() with varying inputs?

I'm new to C and am trying to use fscanf to read from lines of a file of varying lengths

There are 3 different lines that can be read from the file, namely:

string
string char
string char char

I have this:

char elem1;
char elem2;
char *str;

while(fscanf(file, %s%c%c, str, &elem1, &elem2) == 3) {
    ...do stuff
}

So obviously this is fine when I get all 3 expected arguments, but if the line just contained a string then the first two characters of the string on the next line would be assigned to elem1 and 2.

How can I account for that?

Upvotes: 1

Views: 83

Answers (2)

Mark Plotnick
Mark Plotnick

Reputation: 10271

You can use fgets to read in a line at a time, then sscanf to look through just that line for the 1, 2, or 3 items.

char elem1; char elem2; char str[1000]; char line[1000];

while(fgets(line, 1000, file) != NULL) {
    switch(sscanf(line, "%s %c %c", str, &elem1, &elem2)) {
        case 3: /* str, elem1, elem2 are valid */
            break;
        case 2: /* str and elem1 are valid */
            break;
        case 1: /* str is valid */
            break;
    }
}

Upvotes: 2

Mihai Maruseac
Mihai Maruseac

Reputation: 21460

You should read the entire line and the use strtok to get the words on the line.

Edit: See the comment discussion for the benefit of using strtok_r instead of strtok.

Upvotes: 3

Related Questions