سؤال

I am trying to read lines from a text file written in a certain format and want to keep reading as long as it's not the end of the file. However, the program stops right when it gets to this loop. Is this how I would test for EOF without advancing the fscanf?

    while (getchar() != EOF){       //as long as it's not end of file, keep scanning in the following format.
    fscanf(inputFile, "%li*%ll**%^[,]***%^[,]**%^[,]*%i***%^[,]*", &list[i].term, &list[i].sID, &list[i].lastName, &list[i].firstName,
        &list[i].subject, &list[i].catalog, &list[i].section);
    i++;                        //increment array index counter
}
هل كانت مفيدة؟

المحلول

getchar() will read from stdin, but your fscanf(inputFile, ...); will read from inputFile, you cannot use getchar() to check whether you have reached the end of inputFile.

You could use while (fscanf(inputFile, ...) == 7) { to achieve your goal in this case.

From fscanf(3):

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top