如何删除未检查的 return 值警告?

How to remove unchecked return value warning?

我有一个代码,其中我收到未经检查的警告 return 值-

bool check() {
    FILE* fptr = fopen(fi.txt, "r");

    if(fptr != NULL) {
        while(!feof(fptr)) {
            fscanf(fptr, "%s", var1);

            if(strcmp(fptr, var2) == 0) {
                fclose(fptr);
                return true;
            }
        }

        fclose(fptr);
    }

    return false;
}

当我收到这样的警告时,我找到了重写此代码的方法

   Calling fscanf(fptr, "%s", var1) without checking return value. This library function may fail and return an error code.

还有一个方法,这个方法对不对-

if(fptr != NULL) {
    while(fscanf(fptr, "%s", var1) == 0) {
        if(strcmp(var1, var2) == 0) {
            fclose(fptr);
            return true;
        }
        fclose(fptr);
    }
    return false;
}

不要使用 while(feof)。相反,只需检查读取实际数据是否成功。

不要:

    while(!feof(fptr)) {
        fscanf(fptr, "%s", var1);

就这样:

    while(fscanf(fptr, "%s", var1) == 1) {

我不喜欢嵌套的 ifs 错误处理。我很可能更喜欢带有单个 return 点的简短错误处理语句,因为我受到了 by kernel style:

的影响
bool check() {
    FILE* fptr = fopen(fi.txt, "r");
    if (fptr == NULL) goto fopen_failed;   // short error handling with goto-s

    bool ret = false;
    while(fscanf(fptr, "%s", var1) == 1) {
        if(strcmp(fptr, var2) == 0) {
           ret = true;
           break;
        }
    }
    fclose(fptr);

fopen_failed:
    return ret;    // single return point
}