c - fscanf 问题 - 无法从文件中提取字符串

标签 c scanf file-handling fgets

当我使用 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/

相关文章:

c - 为什么我的 C 程序会产生奇怪的 printf 输出?

c - 如何在不复制代码的情况下创建不可转换的 C 类型?

c - Stdin 结构问题

c - 我试图用定界符拆分字符串,但它不起作用,为什么?

c - 使用 sscanf 迭代地解析字符串输入

c - 停在文件末尾

HTML - 像 Web 浏览器通常那样加载图像

c - 由于在 C 中打开新文件而导致数据损坏

c - scanf()将新行char留在缓冲区中

c - c 中的指针更改 static int 值