C - 使用 fscanf 从文件中读取“-1”

C - Using fscanf to read '-1' from a file

我对 C 有点陌生,但基本上我遇到了一个问题,我需要从文件中读取“-1”。遗憾的是,这意味着我 运行 进入文件的过早结束,因为 EOF 常量在我的编译器中也是 -1。

对此有什么变通办法?我可以使用另一个函数来读取它,将 EOF 更改为我可以使用的东西吗?

提前致谢。

人们要求的代码

int read() {
    int returnVal; // The value which we return

    // Open the file if it isn't already opened
    if (file == NULL) {
        file = fopen(filename, "r");
    }

    // Read the number from the file
    fscanf(file, "%i", &returnVal);

    // Return this number
    return returnVal;
}

稍后将此数字与 EOF 进行比较。

好吧,这可能是不好的做法,但我将代码更改为以下内容

int readValue() {
    int returnVal; // The value which we return

    // Open the file if it isn't already opened
    if (file == NULL) {
        file = fopen(filename, "r");
    }

    // Read the number from the file
    fscanf(file, "%i", &returnVal);

    if (feof(file)) {
        fclose(file);
        return -1000;
    }

    // Return this number
    return returnVal;
}

因为我知道我永远不会从我的文件中读取任何这样的数字(它们的范围约为 [-300, 300]。感谢你们的帮助!

fscanf 的 return 值不是读取的值,而是成功读取的项目数,如果发生错误则为 EOF。

问题是您的 read 函数无法区分成功读取和错误情况。您应该将其更改为接受 int * 作为 scanf 写入的参数,并且该函数应该 return 成功读取时为 0,错误时为 -1。您可以使用 scanf 的 return 值作为函数 returns.

的基础

此外,还有一个名为 read 的系统调用,因此您真的应该将其命名为其他名称。并且不要忘记在函数末尾添加 fclose(file),否则你会泄漏文件描述符。