feof()
の直後に確認fscanf()
するか、またはそれ自体からの戻り値を確認する必要がありfscanf()
ます。eofに到達したために新しいデータが読み込まれfscanf()
ないため、最後のデータが繰り返されます。user.username
user.nickname
考えられる修正:
/*
* You could check that two strings were read by fscanf() but this
* would not detect the following:
*
* name1 nickname1
* name2 nickname2
* name3 nickname3
* name4
* name5
*
* The fscanf() would read "name4" and "name5" into
* 'user.username' and 'user.name' repectively.
*
* EOF is, typically, the value -1 so this will stop
* correctly at end-of-file.
*/
while(2 == fscanf(users_file, "%s %s", &user.username, &user.name))
{
printf("%s | %s\n", user.username, user.nickname);
}
また:
/*
* This would detect EOF correctly and stop at the
* first line that did not contain two separate strings.
*/
enum { LINESIZE = 1024 };
char line[LINESIZE];
while (fgets(line, LINESIZE, users_file) &&
2 == sscanf(line, "%s %s", &user.username, &user.name))
{
printf("%s | %s\n", user.username, user.name);
}