简体   繁体   English

C - 从文件中读取

[英]C - reading from file

I'm trying to write a program,in which after pressing the 'v' button on the keyboard it opens a file for reading, and after pressing 'k' it closes the file and also ends the program.我正在尝试编写一个程序,在按下键盘上的“v”按钮后,它会打开一个文件以供读取,并在按下“k”后关闭文件并结束程序。 (There will be more functions in the program, which will individually use the opened file, so it needs to remain open [I know it's a dumb way to design the program, but it's a homework with these rules]). (程序中会有更多的函数,它们会单独使用打开的文件,所以需要保持打开状态[我知道这是一种设计程序的愚蠢方式,但这是有这些规则的作业])。 However, if I want to close the program in the same function main it was opened, but not in the same place, it gives me an error messagae fclose(fr)-fr is not unidentified Can anyone help me?但是,如果我想在它打开的同一函数main关闭程序,但不在同一个地方,它会给我一个错误消息fclose(fr)-fr is not unidentified unidentified 任何人都可以帮助我吗?

Here is my code :这是我的代码:

int main()
{
    char c;
    while(1){
        scanf("%c",&c);
        if(c == 'v'){
            FILE *fr;
            fr = fopen("D:\\Programming\\C\\Projekt\\Projekt 1\\pacienti.txt","r");            
            v();
        }
        else if(c == 'k'){
            fclose(fr);
            return 0;
        }
    }
}

(fclose(fr)-fr is not unidentified (fclose(fr)-fr 不是身份不明的

your code cannot compile because您的代码无法编译,因为

fclose(fr);

use the unknown variable fr使用未知变量fr

To be able to close the previously opened file you need to move FILE *fr;为了能够关闭之前打开的文件,您需要移动FILE *fr; before the while loop, allowing it to be usable in the two branches of the if .while循环之前,允许它在if的两个分支中可用。

I also encourage you to initialize that variable with NULL to avoid undefined behavior if the input k is used before the input v .我还鼓励您使用NULL初始化该变量,以避免在输入k之前使用输入v 时出现未定义的行为。 A proper way is also to test it is not NULL before to call fclose and to set it to NULL after closing the file.一个正确的方法是在调用fclose之前测试它是否为NULL ,并在关闭文件后将其设置为NULL

Anyway fr is only internal to mail and to open the file seems useless, what the function v is doing ?无论如何fr只是邮件内部的,打开文件似乎没用, v函数在做什么?

Out of that very probably you want to replace其中很可能你想更换

scanf("%c",&c);

by经过

scanf(" %c",&c);

to bypass spaces including newline, or better to also check scanf returns 1 to manage EOF case, for instance if stdin redirected to a file.绕过空格,包括换行符,或者更好地检查scanf返回 1 以管理 EOF 情况,例如,如果stdin重定向到文件。

Note if successive v without k are input you open the file several times without closing it.请注意,如果输入不带k 的连续v ,您可以多次打开文件而不关闭它。

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

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