title: Reversing n characters of a file
body: <p>I am trying to write a small program to reverse the first n characters of the text in a file. I wrote this::</p>
  
  <pre><code>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&lt;n;++i)
          ch[i]=fgetc(fp);
      rewind(fp);
      printf("%.*s\n",n,ch); //printing the 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 to reverse:: ");
      scanf("%d",&amp;n);
      reverse(fp,n);
      rewind(fp);
      printf("After reversing text is::\n");
      printdata(fp);
      fclose(fp);
      return 0;
  }
  </code></pre>
  
  <p>And the output is 
  <img src="https://i.stack.imgur.com/8Mpc5.png" alt="enter image description here"></p>
  
  <p>Where am i going wrong? Why is there a 'u' ?
  <strong>EDIT</strong>: I could get it work by replacing the while loop with</p>
  
  <pre><code>for( int i=0;i&lt;n;++i)
          fputc(ch[n-1-i],fp);
  </code></pre>
  
  <p>But what is the fault in the while?</p>