Reputation: 59
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.
(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?
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;
}
}
}
Upvotes: 1
Views: 335
Reputation: 32596
(fclose(fr)-fr is not unidentified
your code cannot compile because
fclose(fr);
use the unknown variable fr
To be able to close the previously opened file you need to move FILE *fr;
before the while
loop, allowing it to be usable in the two branches of the 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. 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.
Anyway fr is only internal to mail and to open the file seems useless, what the function v is doing ?
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.
Note if successive v without k are input you open the file several times without closing it.
Upvotes: 2