gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:34:37 25 4
gpt4 key购买 nike

我是 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/

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