C 在 fscanf 中使用 char* 导致错误段错误 : 11

标签 c

我是 C 的新手,在使用 fscanf 从 .txt 文件中读取所有字符串时遇到了一个问题。

代码如下:

#include <stdlib.h>
#include <stdio.h>

int main() {
    FILE *spIn;
    char *numIn;

    spIn = fopen("data.txt", "r");

    if (spIn == NULL) {
        printf("Can't Open This File \n");
    }

    while ((fscanf(spIn, "%s", numIn)) == 1) {
        printf("%s\n", numIn);
    };

    fclose(spIn);
    return 1;
}

这会引发错误:Segmentation fault: 11

txt文件的原始数据是:

1 2 345 rrtts46
dfddcd gh 21
789 kl

整数、字符串、空格和换行符的混合体。

最佳答案

至少 4 个可能导致某种错误的候选未定义行为 (UB)。

  1. 代码无法将已初始化的指针传递给 fscanf(spIn,"%s",numIn)
  2. 即使 fopen() 失败,代码也会调用 fscanf()
  3. 即使 fopen() 失败,代码也会调用 fclose()
  4. fscanf(spIn,"%s",numIn)) 没有宽度限制,比 gets() 差.

文本文件确实没有字符串('\0' 终止数据)也没有int,它们有(以 '\n' 结尾的各种字符)。

要读取并保存为字符串,请使用fgets()。不要使用 fscanf() 读取数据行。

#include <stdlib.h>
#include <stdio.h>

int main() {
  FILE *spIn = fopen("data.txt", "r");
  if (spIn == NULL) {
    printf("Can't Open This File \n");
  } else {
    char buf[100];
    while (fgets(buf, sizeof buf, spIn)) {
      printf("%s", buf);
    }
    fclose(spIn);
  }
}

关于C 在 fscanf 中使用 char* 导致错误段错误 : 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66517648/

相关文章:

c - 从文本文件填充 C 中的二维数组

C 预处理器条件指令优先级和嵌套

c - 这个 C 模式程序有什么问题

计算随机c文件中的注释字符数

c++ - 如何忽略 getopt_long 中的无效选项

c - 向 pthread 发送信号以中止休眠

c - 收缩 int 数组 C

c - dup2 的问题

c - 我的功能不工作 'name.exe has stopped working'

c - UML 中的用户模式内核如何与主机上的底层内核接口(interface)