【问题标题】:C - Using fscanf to read '-1' from a fileC - 使用 fscanf 从文件中读取“-1”
【发布时间】:2015-09-11 16:54:53
【问题描述】:

我对 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]。感谢你们的所有帮助!

【问题讨论】:

  • EOF 常量为 -1 并不重要...永远不会出现您检查已读取的值并由于 -1 以外的任何原因返回为 -1 的情况在那里(或者没有读取任何内容并且您的内存恰好包含-1)。发布您认为遇到问题的代码,您可以得到帮助,但如果没有这些代码,则按照 Stack Overflow 标准,这个问题是不完整的。

标签: c eof scanf


【解决方案1】:

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

【讨论】:

  • @Mildan fscanf 至少提供两个值:函数状态作为其返回值,以及格式要求/指针指定的值论点。好好阅读手册页。您应该始终检查scanf 系列的返回值以及感兴趣的值的范围。
  • 所以我应该添加一个检查以查看 fscanf 是否返回
  • @Mildan 你检查它是否返回你想要阅读的项目数,在这种情况下是1。如果不是,您将需要一个后备策略,或者作为另一个答案,通过将其设置为 int readval(int* returnVal) 并将 fscanf 参数从 &returnVal 更改为 returnVal 并将其传递回调用者返回 returnVal 时,您将返回来自 fscanf 的返回值。使困惑?不要使用readreturnVal 之类的标识符。
【解决方案2】:

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

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

【讨论】:

  • 我会尝试他们两个;)
猜你喜欢
  • 2020-03-20
  • 1970-01-01
  • 2013-05-06
  • 1970-01-01
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
相关资源
最近更新 更多