writes:
> #include <stdio.h>
>
> int main()
> {
> FILE *fp;
> char s[100];
>
> fopen("file.txt","w+");
>
> fprintf(fp,"HI\n");
>
> fclose(fp);
> fscanf(fp,"%s",s);
> printf("%s\n",s);
> }
>
> I know this will invoke undefined behaviour.Does undefined behavior
> mean it MIGHT also work as expected in this case?Is it possible to read
> from a file which already closed at least once out of 1000 times on
> thousand different environment?
If your program invokes undefined behavior, it's always possible that
it will behave as you expect, whatever your expectations happen to be.
(That's not quite true; if you expect it to do something physically or
logically impossible, that's not going to happen -- but as far as the
standard is concerned, anything is possible.)
In this particular case, assuming you assign the result of fopen() to
fp, if the program displays "HI", it *probably* indicates that the
implementation is broken (e.g., fclose() doesn't work properly). If
the breakage only shows up for programs that invoke undefined
behavior, the implementation could still be conforming.
More realistically, consider something like this:
fp1 = fopen("some_file", "r");
...
fclose(fp1);
fp2 = fopen("another_file", "r");
fscanf(fp1, "%s", s);
Since fp1 is closed before fp2 is opened, it's plausible that fopen()
could return the same pointer value for both. In this case, reading
from fp1, even though it's closed, would most likely read from
"another_file". (I've just demonstrated this in a small program.)
As I'm sure you know, the lesson is: Don't do this.
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.