Andrew said:
Sorry, Let me try to re-phrase this with a simple example. The
following code writes the letter A and an additional 10 bytes (1 for
each call to fgetc) to the output file . I am wondering why this
happens and if there is a way I can avoid it. I don't believe fflush
is suppose to be used on this type of stream? Although, I tried
fflush(of) and it worked, but I suspect it would have wiped out any
previous information which the file contained that I might want to
preserve. Thanks for any advice.
#include <stdio.h>
int main() {
FILE *of;
int i;
if((of = fopen("c:\\problem.txt", "w")) == NULL) {
if((of = fopen("c:\\problem.txt", "r+")) == NULL) {
This looks a bit scary, but it basically says "if I can't create it, I want
to open it read-write instead". If that's what you want, then fair enough.
printf("\nFile Error");
}
}
/* Without a fputc call before the loop the problem does
not exist */
fputc(65,of);
This doesn't write 'A', by the way - it writes whatever character happens to
have the value 65 on the system you're running it on. (Let me guess - 'A'
on your system, right? But on, say, an IBM mainframe, you'd get a different
result.)
fputc('A', of); conveys your intent more clearly /and/ is portable.
/* tried fflush(of) here but I think this is undefined?
No, you're fine with fflush() on streams open for output or update.
and it seems to clear any previous contents
stored before program execution */
That's not fflush()'s fault. That's your "w" mode talking (remember those
fopen() calls above?). Swap it around with your "r+".
/* 10 can be replaced with any number larger than the
input file size */
for(i = 0; i < 10; i++)
fgetc(of);
If the file was successfully created ("w" mode), there's nothing to read, is
there? So fgetc() will return EOF, to indicate that it couldn't fulfil your
request. I note that your program is not checking the return value of
fgetc. If you add a check, you will find that fgetc is returning EOF on
each call.