tags:

views:

63

answers:

2

If I open a file and use fscanf to read a file like this:

2 41
1 50
1 46
....

How do I tell C to read the first number and store it as a variable, then the second as another variable, run a loop, then move on to the next set?

A: 

Some pointers about fscanf:

  1. Always check the return value. If you asked for one integer, it should return 1 if it scanned successfully. Other return values include 0 or EOF, which may indicate a failure in reading, or a failure in finding data matching the provided pattern.

  2. Whitespace characters are usually ignored unless the format specification includes an [, c or n specifier.

  3. Always check the return value.


while(1)
{
    int result;
    int firstNumber;
    int secondNumber;

    result = fscanf (file, "%d%d", &firstNumber, &secondNumber);
    if (result == 2)
    {
        printf("Scanned two numbers, %d and %d\n", firstNumber, secondNumber);
    }
    else
    {
        if (result != EOF)
            puts("An error occurred");
        break;
    }
}
dreamlax
A: 

A loop like this is what you're after:

int type, stories;

while (fscanf(buildingFile, "%d %d", &type, &stories) == 2)
{
    printf("Got type=%d, stories=%d\n", type, stories);
    /* Do something with 'type' and 'stories' */
}

if (ferror(buildingFile))
{
    perror("buildingFile");
}
caf