The fscanf()
function will scan text according to the format string you provide, leaving unconsumed anything it cannot match to the format. With the format you present, it will consume any leading whitespace and then try to match whatever follows to a possibly-signed decimal integer. It will return 1
if it successfully matches an (one) integer, and 0
if it encounters non-whitespace that it cannot match as an integer. It will return EOF
only in the event that it reaches EOF
while consuming the leading whitespace.
Therefore, if your file contains anything other than whitespace and decimal numbers, the scan will eventually reach a point where it cannot parse a number from the input (and therefore returns 0
without consuming anything), but you keep asking it to try again.
What you could do instead depends on the format of the file, and on what you mean by "count line numbers". Based on your wording and your scanf()
format, I first thought your data had literal line numbers in it (like, for instance, BASIC or Fortran source code might have), and you wanted to count those. I now suspect that what you meant is that you simply want to count the number of lines. If that's what you are after then you might do something like this:
char c;
size_t count = 1;
while (fscanf(Fr, "%*[^\n]%c", &c) == 1) {
count += 1;
}
That scanf()
format scans and ignores everything up to a newline or EOF, then consumes the next character if there is one (which can only be a newline). It returns 1
if and only if it successfully scans a newline. Initializing count
to 1
corresponds to viewing the newlines as line separators, as opposed to line terminators, so that there is one more line than there are newlines.
There are other approaches, too, and it may be that the one above doesn't suit you perfectly, but it should give you an idea of how you can proceed.