c - Reversing n characters of a file -
i trying write small program reverse first n characters of text in file. wrote this::
void getdata(file *fp) { char ch; printf("enter text::\n"); while((ch=getchar())!=eof) fputc(ch,fp); } void printdata(file *fp) { char ch; while((ch=fgetc(fp))!=eof) putchar(ch); } void reverse(file *fp, int n) { char ch[20]; for( int i=0;i<n;++i) ch[i]=fgetc(fp); rewind(fp); printf("%.*s\n",n,ch); //printing string while(n--) fputc(ch[n-1],fp); } int main() { file *fp; int n; fp=fopen("music.txt","w+"); getdata(fp); rewind(fp); printf("number of chars reverse:: "); scanf("%d",&n); reverse(fp,n); rewind(fp); printf("after reversing text is::\n"); printdata(fp); fclose(fp); return 0; } and output 
where going wrong? why there 'u' ? edit: work replacing while loop with
for( int i=0;i<n;++i) fputc(ch[n-1-i],fp); but fault in while?
the fault in while first loop decrement n. in use case n start 4 instead of 5. assign char @ n-1, means n has start 5. @ end loop 4 time long instead of 5.
change
while(n--) fputc(ch[n-1],fp); to
do { fputc(ch[n-1],fp); }while(--n); another little thing. reverse function not checking n passed cannot > of ch length, in case 20.
Comments
Post a Comment