c - 初学者对使用 fscanf 的 while 语句感到困惑

标签 c file scanf

下面是一个我试图理解的程序。我唯一感到困惑的部分是 while 语句是 while fscanf(....) == 4 以及 if(...) == 0.

有人可以向我解释一下这条线及其用途吗?

#include <stdio.h>
#include <stdlib.h>


struct str_student {
    char UFID[9];
    char firstname[20];
    char major[10];
    int age;
};


 int main(int argc, char *argv[]) {
     FILE *fStud = fopen("students.dat", "r");
     struct str_student S[11];

    int i, n = 0;
    while( fscanf(fStud, "%s %s %s %i", S[n].UFID, S[n].firstname, S[n].major, &S[n].age) == 4)          
    {    if(( S[n].age > 40 ) && ( strcmp(S[n].major, "ECE") == 0 ))
            n = n + 1;
    }

    printf("\nStudents of the ECE Department who are 41 or more years old:\n");
    for( i=0; i<n; i++ ) {
         printf("%s\n", S[i].UFID);
    }

    return 0;
 }

最佳答案

fscanf 返回读取的字段数。格式字符串 "%s %s %s %i" 有四个字段,所以 while (fscan(...) == 4) 循环只要 fscanf 能够读取所有四个字段。如果遇到文件结尾 (EOF),或者文件包含格式不正确的数据(例如 %i 字段不是有效整数),它将退出。

strcmp 如果两个字符串匹配则返回 0。 if (strcmp(a, b) == 0) 是 C 中检查两个字符串是否相等的最常用方法。

关于c - 初学者对使用 fscanf 的 while 语句感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27512649/

相关文章:

c - 如何 fscanf 文件并根据行的第一个字符将行中的数据存储在不同的变量中?

Java JNI - 无法在 AMD 64 位平台上加载 IA 32 位 .dll

c++ - C/C++ 中 unsigned 关键字的混淆

c - 为什么 fopen 文件夹失败?

java - 使用 java 应用程序解压缩时文件权限被拒绝,手动工作正常

iOS:如何找到文件的创建日期?

c++ - 如何捕获 sscanf 字符串的长度?

c - 将 char** 类型的数组作为 void** 类型的参数传递会给出意外警告

c - 使用 clock_gettime 和 struct stat.mtim 的时序偏差

c - 无法通过函数向数组添加项目 (C)