gpt4 book ai didi

c - 向后读取文本文件并放入 C 中

转载 作者:行者123 更新时间:2023-11-30 15:14:07 24 4
gpt4 key购买 nike

I want to know how to read a text file backwards in C.

Frozen_snowman.txt 是

Do you wanna build a snowman?
Come on lets go and play
I never see you anymore
Come out the door
It's like you've gone away-
We used to be best buddies
And now we're not
I wish you would tell me why!-
Do you wanna build a snowman?
It doesn't have to be a snowman.

代码

#include<stdio.h>
int main()
{
int i;
char buffer[100];
char *a[100];
FILE *f,*p;
f=fopen("Frozen_snowman.txt","r");
p=fopen("Reverse.txt","w");
for(i=0;i<10;i++)
{
fgets(buffer,100,f);
a[i]=buffer;
}
for(i=9;i>-1;i--)
{
fputs(a[i],p);
}

return 0;
}

结果是

It doesn't have to be a snowman.
It doesn't have to be a snowman.
It doesn't have to be a snowman.
It doesn't have to be a snowman.
It doesn't have to be a snowman.
It doesn't have to be a snowman.
It doesn't have to be a snowman.
It doesn't have to be a snowman.
It doesn't have to be a snowman.
It doesn't have to be a snowman.

Why is that?

最佳答案

原因是这样的 -

fgets(buffer,100,f);       // check return of fgets
a[i]=buffer; // Note - buffer is modified in each iteration

您指向最后一次迭代中存储在缓冲区中的字符串。每个指针都指向最后读取的字符串。每次打印时都会打印相同的字符串。

您应该做的是分配内存给指针a[i],并使用strcpy复制字符串。

关于c - 向后读取文本文件并放入 C 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34180537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com