FILE *p as a global var; fflush() in lite-c

Posted By: Zheka

FILE *p as a global var; fflush() in lite-c - 02/16/18 12:46

Hello,

There are several things which I cannot get to work (Zorro).

Consider the following code;
Quote:
FILE *p;

main ()
{
int tmp=3;
p=fopen("d:\myfile.csv",w+b);
fwrite(&tmp,sizeof(int),1,p);
fclose(p);
}

run()
{
int tmp;
p=fopen("d:\myfile.csv",rb);
fread(&tmp,sizeof(int),1,p);
printf(" n PB=%i", tmp);
fclose(p);
}


Questions:

1. If I skip closing the file in main() and re-opening it in run(), the result of printf() is 0.
Since *p is defined globally, I would expect it to keep its value, and then be able to read from the file p, still seemingly open.
Why doesn't that work?

2. to implement (1), If I do fflush(p) in main() instead of fclose(), I can see that the data are not physically written to a file (as would be expected).
Are there any nuances to it?

Thank you in advance for help.
Posted By: Petra

Re: FILE *p as a global var; fflush() in lite-c - 02/16/18 16:09

Skipping and not opening is not good, the file handle is still open with "w+b". You cant read a variable from such a file handle.
Posted By: Zheka

Re: FILE *p as a global var; fflush() in lite-c - 02/16/18 16:26

But it is written everywhere that w+ opens file for both - writing AND reading.
https://www.cprogramming.com/tutorial/cfileio.html

Where is the catch?
© 2024 lite-C Forums