The flow is as such:
- You create a file (reset it to an empty file if it exists). That's what the
"w"
mode does. - Then you write stuff. Note that the file position is always considered to be at the very end, as writing moves the file position.
- Now you try to read from the end. The very first thing you read would be an EOF already. Indeed, when I try your program on my Mac, I just get a single strange character just as one would expect from the fact that you're using a
do { } while
. I suggest you instead do something like:for (c = getc(f1); c != EOF; c = getc(f1)) { putchar(c) }
or similar loop. - But also, your reading should fail anyway because the file mode is
"w"
(write only) instead of"w+"
.
So you need to do two things:
- Use file mode
"w+"
. - Reset the file position to the beginning of the file after writing to it:
fseek(f1, 0, SEEK_SET);
.