在 C 语言中读取文件中的名称

Reading names in a file in C

提问人:kyori 提问时间:3/9/2012 更新时间:3/9/2012 访问量:3419

问:

我有一个这样的文件:

name1 nickname1
name2 nickname2
name3 nickname3

我希望我的程序读取该文件并显示名称/昵称情侣。

这是我所做的:

users_file = fopen("users", "r");

  while(!feof(users_file))
  {
    fscanf(users_file, "%s %s", &user.username, &user.name);
    printf("%s | %s\n", user.username, user.nickname);
  }

这是输出:

 name1 | nickname1 
 name2 | nickname2      
 name3 | nickname3 
 name3 | nickname3

为什么最后一个重复? 谢谢

c 扫描 feof

评论


答:

3赞 hmjd 3/9/2012 #1

您需要在 之后立即检查,或者,或者,检查其本身的返回值。最后一个是重复的,因为没有读取任何新数据,并且由于到达了 eof。feof()fscanf()fscanf()fscanf()user.usernameuser.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);
}
1赞 Richard J. Ross III 3/9/2012 #2

如果将循环更改为:

while((fscanf(users_file, "%s %s", &user.username, &user.name))
{
    printf("%s | %s\n", user.username, user.nickname);
}

然后它应该可以工作,请注意,我们不检查 EOF,我们让 fscanf 为我们检查。

0赞 Vatine 3/9/2012 #3

如果看到文件结束条件,则该函数返回 true。如果您正在从文件中读取,则情况可能并非如此。feof()

有多种方法可以解决这个问题,可能起作用的东西(基本上是 hmjd 所说的)是:

while (fscanf(users_file, "%s %s", &user.username, &user.name) == 2) {
  ...
}

的返回值是成功转换和分配的转换次数,因此,如果您在读取时获得 EOF,这将与您预期的两个不同。fscanf