简体   繁体   English

反转文件的n个字符

[英]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. 我正在尝试编写一个小程序来反转文件中文本的前n个字符。 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 输出是 在此处输入图片说明

Where am i going wrong? 我要去哪里错了? Why is there a 'u' ? 为什么会有“ u”? EDIT : I could get it work by replacing the while loop with 编辑 :我可以通过替换while循环来使其工作

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

But what is the fault in the while? 但是,这有什么问题呢?

The fault in your while is that first loop decrement n . 您这时的错误是第一个循环递减n In your use case n start from 4 instead of 5 . 在您的用例中, n4而不是5 Then the you assign the char at n-1 , that means that the n has to start from 5 . 然后,您将字符分配给n-1 ,这意味着n必须从5开始。 At the end your loop is 4 time long instead of 5 . 最后,循环长4倍而不是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. 在您的情况下,您的反向功能不是检查传递的n是否不能大于ch长度。

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. 在控制到达fputc(ch[n-1],fp) while(n--)之后的while循环中fputc(ch[n-1],fp) n已经减小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM