gpt4 book ai didi

c - 我的 fgets 实现像 fgets 一样读取实际内容,但如果在文件中找到 NULL 字符串,它会读取垃圾?

转载 作者:太空宇宙 更新时间:2023-11-04 07:06:40 32 4
gpt4 key购买 nike

我已经实现了我自己的 fgets(即 myfgets)。当我的文件中有必须由 myfgets 函数读取的 NULL 字符串时,它会打印所有字符串(好)但有一些垃圾(坏),但如果我使用预定义 fgets 那么就没有垃圾了。下面是我的代码和文件内容,其中包含 NULL 字符串。

我的文件

hello word NULL 早上好//如果 NULL 被删除那么它很好

#include<stdio.h>
#include<stdlib.h>
char *myfgets(char *Buffer_address,int size,FILE *fp)
{
register int c;
register char *I_help_Notify_IfNotRead;
I_help_Notify_IfNotRead = Buffer_address;

while(--size>0 && (c=getc(fp))!=EOF )
{
if((*I_help_Notify_IfNotRead++=c)=='\n')
break;
*I_help_Notify_IfNotRead='\0';
}

return ( c==EOF && I_help_Notify_IfNotRead == Buffer_address ) ? NULL : Buffer_address;
}

int main()
{
char ch[100];
FILE *fp ;
fp=fopen("myfile","r");
char * pp=(myfgets(ch,100,fp));
printf("%s",pp);

exit(EXIT_SUCCESS); // No need to close(fp) because exit does for us
}

输出:

hello word NULL Good Morning (good)

E����[�s^� (garbage) // Why am I getting this but not with predefine fgets?

最佳答案

您以 null 终止字符串的逻辑已损坏。您在每个字符后写入一个 NUL 字节, 最后一个字符除外。将写入 NUL 的行移动到循环之后。

顺便说一句,我见过比 I_help_Notify_IfNotRead 更糟糕的变量名,但并不常见。 out 出了什么问题?

关于c - 我的 fgets 实现像 fgets 一样读取实际内容,但如果在文件中找到 NULL 字符串,它会读取垃圾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32418328/

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