fopen - displaying contents of a file on monitor in C -
i'm trying recreate program saw in class. teacher made file 10 lines, showed file indeed created, , displayed contents. code doesn't work reason, prints looks a"=" million times , exits.
my code:
void main() { file* f1; char c; int i; f1=fopen("essay 4.txt","w"); for(i=0;i<10;i++) fprintf(f1," essay deserves 100!\n"); { c=getc(f1); putchar(c); }while(c!=eof); }
what problem? far can see did in example given.
the flow such:
- you create file (reset empty file if exists). that's
"w"
mode does. - then write stuff. note file position considered @ end, writing moves file position.
- now try read from end. first thing read eof already. indeed, when try program on mac, single strange character 1 expect fact you're using
do { } while
. suggest instead like:for (c = getc(f1); c != eof; c = getc(f1)) { putchar(c) }
or similar loop. - but also, reading should fail anyway because file mode
"w"
(write only) instead of"w+"
.
so need 2 things:
- use file mode
"w+"
. - reset file position beginning of file after writing it:
fseek(f1, 0, seek_set);
.
Comments
Post a Comment