【发布时间】:2015-12-01 19:24:41
【问题描述】:
我已经实现了自己的fgets(即myfgets)。当我的文件中有 NULL 字符串必须由 myfgets 函数读取时,它会打印所有字符串(好)但有一些垃圾(坏),但如果我使用预定义 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?
【问题讨论】:
-
*I_help_Notify_IfNotRead='\0';应该在循环之后。此外,如果您的文件为空,则行为未定义(c未设置);只需删除c==EOF &&。 NULL 是指一个 NUL 字符吗?