Reading character by character from a file in C -
i wrote following program :
int main(){ char str[500],c; file *f1=fopen("input.txt","r"); file *f2=fopen("output.txt","w"); while(c=fgetc(f1)!=eof) fputc(toupper(c),f2); fclose(f1); } i not getting desired result though. rewrote code using while loop.
int main(){ char str[500]; file *f1=fopen("input.txt","r"); file *f2=fopen("output.txt","w"); char c; { fputc(toupper(c),f2); c=fgetc(f1); }while(c!=eof); } i figured out reason first code fails because in while loop while(c=fgetc(f1)!=eof), cannot guarantee left part of != evaluated first , hence results not proper. correct explanation?
yes correct; in first code while loop written wrongly:
while(c=fgetc(f1)!=eof) should be:
while((c=fgetc(f1))!=eof) // ^ ^ added parenthesis because precedence of operator != greater = operator in conditional expression c=fgetc(f1)!=eof, first returned result of comparing value fgetc() eof (either 0 or 1) , assigned c. (that means c=fgetc(f1)!=eof expression equivalent c=(fgetc(f1)!=eof) , not need.)
you need () overwrite precedence suggested.
but have second thing improve c variable must int (not char) in order hold eof-value.
Comments
Post a Comment