简体   繁体   English

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

[英]C - Using fscanf to read '-1' from a file

I'm a bit new to C, but basically I have a problem where I need to read '-1' from a file.我对 C 有点陌生,但基本上我有一个问题,我需要从文件中读取“-1”。 Sadly this means I run into a premature ending of the file, because the EOF constant is also -1 in my compiler.可悲的是,这意味着我遇到了文件的过早结束,因为 EOF 常量在我的编译器中也是 -1。

What sort of work arounds would there be for this?对此会有什么样的解决方法? Is there another function I can use to read it that will change the EOF to something I can work with?我可以使用另一个函数来读取它,它将 EOF 更改为我可以使用的东西吗?

Thanks in advance.提前致谢。

The code since people are asking for it代码,因为人们要求它

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;
}

This number is then later compared to EOF.然后将该数字与 EOF 进行比较。

Okay this is probably bad practice, but I changed the code to the following好的,这可能是不好的做法,但我将代码更改为以下内容

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;
}

Because I knew I would never read any such number from my file (they range from about [-300, 300]. Thanks for all your help guys!因为我知道我永远不会从我的文件中读取任何这样的数字(它们的范围大约是 [-300, 300]。感谢你们的帮助!

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

The problem is that your read function doesn't distinguish between a successful read and an error condition.问题是您的read功能无法区分成功读取和错误情况。 You should change it to accept a int * as a parameter that scanf writes into, and the function should return something like 0 on a successful read and -1 on error.您应该将其更改为接受int *作为scanf写入的参数,并且该函数应该在成功读取时返回类似 0 的内容,在错误时返回 -1 。 You can use the return value of scanf as the basis of what your function returns.您可以使用scanf的返回值作为函数返回内容的基础。

Also, there's a system call named read , so you should really name it something else.此外,还有一个名为read的系统调用,因此您应该真正将其命名为其他名称。 And don't forget to fclose(file) at the end of the function, otherwise you're leaking file descriptors.并且不要忘记在函数末尾使用fclose(file) ,否则您会泄漏文件描述符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM