Lokesh Jaddu
Lokesh Jaddu

Reputation: 53

Reversing n characters of a file

I am trying to write a small program to reverse the first n characters of the text in a file. I 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 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",&n);
    reverse(fp,n);
    rewind(fp);
    printf("After reversing text is::\n");
    printdata(fp);
    fclose(fp);
    return 0;
}

And the output is enter image description here

Where am i going wrong? Why is there a 'u' ? EDIT: I could get it work by replacing the while loop with

for( int i=0;i<n;++i)
        fputc(ch[n-1-i],fp);

But what is the fault in the while?

Upvotes: 1

Views: 2660

Answers (2)

LPs
LPs

Reputation: 16213

The fault in your while is that first loop decrement n. In your use case n start from 4 instead of 5. Then the you assign the char at n-1, that means that the n has to start from 5. At the end your loop is 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. Your reverse function is not checking that n passed cannot be > of ch length, in your case 20.

Upvotes: 1

Gaurav Sehgal
Gaurav Sehgal

Reputation: 7542

for( int i=0;i<n;++i)   //consider n as 5
    fputc(ch[n-1-i],fp);//  ch[5-1-0] ch[5-1-1] ch[5-1-2] ...

is not equivalent to

while(n--)              //consider n as 5
    fputc(ch[n-1],fp);  //ch[4-1] ch[3-1] ....

in while loop after while(n--) when control reaches fputc(ch[n-1],fp) n has already decremented.

Upvotes: 0

Related Questions