当我使用 getc 时,该程序正在运行,但它不适用于此代码。 我尝试在 while 循环内打印随机文本,但它打印为 NULL。
void main()
{
FILE *fp;
char *str=NULL;
char s;
fp=fopen("text.txt","r");
if(fp==NULL)
{
printf("\nCAN NOT OPEN FILE");
exit(EXIT_FAILURE);
}
while(fscanf(fp,"%s",str)!=EOF)
{
printf("%s",str); //not taking any values in str,prints NULL
}
fclose(fp);
}
最佳答案
问题出在这个声明上:
char *str=NULL;
由于您使用 fscanf
读取字符数组中的单词,因此您必须将它们读入有效的内存位置。因此 str
应该是一个 char
数组,其长度应等于文件中最长的单词加 1(用于空终止)。
因此将上面的内容更改为:
char str[256];
7.21.6.2 The fscanf function
...12 The conversion specifiers and their meanings are:
s - Matches a sequence of non-white-space characters. If no l length modifier is present, the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically.
关于c - fscanf 问题 - 无法从文件中提取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52360022/