Search code examples
cfgetsscanf

A way to fscanf on only the first line


I've been looking into a way to obtain 2 integers, seperated by a space, that are located in the first line of a file that I would read. I considered using

fscanf(file, "%d %d\n", &wide, &high);

But that read 2 integers that were anywhere in the file, and would give the wrong output if the first line was in the wrong format. I also tried using

char line[1001];
fgets(line, 1000, file);

Which seems like the best bet, except for how clumsy it is. It leaves me with a string that has up to a few hundred blank spaces, from which I must extract my precious integers, nevermind checking for errors in formatting.

Surely there is a better option than this? I'll accept any solution, but the most robust solution seems (to me) to be a fscanf on the first line only. Any way to do that?


Solution

  • You can capture the character immediately following the second number in a char, and check that the captured character is '\n', like this:

    int wide, high;
    char c;
    if (fscanf(file, "%d%d%c", &wide, &high, &c) != 3 || c != '\n') {
        printf("Incorrect file format: expected two ints followed by a newline.");
    }
    

    Here is a demo on ideone.