It should read a file and give out its reverse in another file. Here it is:
The code in blue is causing all the problems. First it was printing absurd characters like squares and upside down question marks, but then I fixed it to print only those characters which are in the file. But still I'm not getting the output I was expecting.Code:#include<stdio.h> int main() { char temp[200],ch; int x,lol; int flag=0; FILE *inf,*outf; inf=fopen("/home/abhishek/Desktop/shakespear.txt","r"); if(inf==NULL) { printf("\nError opening input file"); return 1; } outf=fopen("/home/abhishek/Desktop/reverse.txt","w"); if(outf==NULL) { printf("\nError opening output file"); return 1; } while(flag==0) { for(x=0;x<200;x++) { if((ch=fgetc(inf))!=EOF) { temp[x]=ch; lol=x; } else flag=1; } for(x=lol;x>=0;x--) fputc(temp[x],outf); } printf("\nDone!"); return 0; }
shakespear.txt
Welcome to the Web's first edition of the Complete Works of William Shakespeare. This site has offered Shakespeare's plays and poetry to the Internet community since 1993.
Consider that you have an array of 5 characters in size. The user enter 10 characters! That means 10 characters + 1 (for the ending '\0') is written to your array. But your array is only 5 chars long! Uh-oh!
What can happen? Well, the result is undefined. Basically that means the result is not defined. Defined as in that we know the behavior. In undefined, we cannot guarantee what will happen.
First and foremost - it's a security risk. Lots of malware and other security threats take advantage of buffer overruns to run malicious code.
reverse.txt
The output is all scatteredevah uoy taht redisnoC
.3991 ecnis ytinummoc tenretnI eht ot yrteop dna syalp s'eraepsekahS dereffo sah etis sihT .eraepsekahS mailliW fo skroW etelpmoC eht fo noitide tsrif s'beW eht ot emocleW neppah nac tahW
!ho-hU !gnol srahc 5 ylno si yarra ruoy tuB .yarra ruoy ot nettirw si )'0\' gnidne eht rof( 1 + sretcarahc 01 snaem tahT !sretcarahc 01 retne resu ehT .ezis ni sretcarahc 5 fo yarra na s'ti - tsomerof dna tsriF
.neppah lliw tahw eetnaraug tonnac ew ,denifednu nI .roivaheb eht wonk ew taht ni sa denifeD .denifed ton si tluser eht snaem taht yllacisaB .denifednu si tluser eht ,lleW ?.edoc suoicilam nur ot snurrevo reffub fo egatnavda ekat staerht ytiruces rehto dna erawlam fo stoL .ksir ytiruces a
What's wrong?