提问人:Keller 提问时间:2/1/2023 更新时间:2/1/2023 访问量:66
fscanf 分段错误,尝试读取文件并将值放入数组中 - C
fscanf segmentation fault, trying to read a file and put values in an array - c
问:
我的朋友正在为考试而学习。他不断收到“while (fscanf(f, ”%s %d %d“, A[i].costruttore, A[i].ns, A[i].costo) != EOF)”的分段错误。 我该如何帮助他?
你可以在下面找到他的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DIM 100
typedef struct
{
char costruttore[20];
int ns;
int costo;
} memoria;
void lettura(memoria A[], int *n)
{
int i = 0;
FILE *f;
f = fopen("memory.txt", "r");
if( f == NULL ) {
fprintf(stderr, "Couldn't open %s: %s\n", "memory.txt", strerror(errno));
exit(1);
}
while (fscanf(f, "%s %d %d", A[i].costruttore, A[i].ns, A[i].costo) != EOF)
i++;
(*n) = i;
fclose(f);
for (i = 0; i < (*n); i++)
printf("%s %d %d\n", A[i].costruttore, A[i].ns, A[i].costo);
}
int main()
{
memoria A[DIM];
int n;
lettura(A, &n);
return 0;
}
memory.txt内容
PerKele 56 41
AM-Silicon 49 41
JKR 33 50
Atlantic 57 62
JADA 50 50
JKR 40 51
Drast 28 35
SGUZ 73 55
JADA 29 46
FARSTIC 65 30
Drast 41 36
FRoW 48 67
FARSTIC 39 62
Drast 27 44
SGUZ 51 50
Drast 58 60
Liquid 41 71
SWP3 50 63
KRRAM 54 24
YTK 32 60
ALOE 37 57
HAL 53 39
AM-Silicon 59 50
Atlantic 24 42
ALOE 31 46
JADA 38 65
Nikit 48 49
PerKele 68 37
HAL 46 53
TOO 73 60
HAL 31 37
YTK 39 55
Nikit 57 47
FARSTIC 40 47
AM-Silicon 68 52
HAL 50 50
JADA 32 37
FRoW 47 53
SWP3 50 50
FRoW 52 52
JADA 63 58
Liquid 47 46
Drast 36 54
ALOE 44 30
HAL 39 33
Drast 48 41
SWP3 52 56
KRRAM 65 56
他试图将&放在“A[i].costruttore, A[i].ns, A[i].costo”中,但没有奏效。
答:
0赞
Carson
2/1/2023
#1
@jabberwocky如前所述,fscanf 中需要指针,但这些指针仅适用于 and 字段。costo
ns
下面是具有正确结构的 OPs 代码的等效示例:
#include <stdio.h>
#define DIM 100
typedef struct record {
char f0[20];
int f1, f2;
} record_t;
int main (void) {
FILE *f = fopen("memory.txt", "r");
record_t records[DIM];
int i = 0;
while (fscanf(f, "%s %d %d", records[i].f0, &records[i].f1, &records[i].f2) != EOF) {
i++;
}
fclose(f);
}
这将运行,并产生正确的结果。如果没有前面的 和 ,它将出现段错误。&
f1
f2
评论
0赞
chux - Reinstate Monica
2/1/2023
“但是,这些只需要 Costo 和 NS 字段。” --> 不完全是。指针也需要。注意;这是正确的,并且当作为函数参数传递时是一个指针,即使没有 ."%s"
records[i].f0
&
0赞
Keller
2/1/2023
谢谢,不再有分段错误。但现在的问题是代码不起作用。
2赞
chux - Reinstate Monica
2/1/2023
#2
节省时间,启用所有编译器警告
这是这里的#1课程。
“%d”
匹配 int *
,而不是 fscanf()
中的 int
使用 .int
// fscanf(f, "%s %d %d", A[i].costruttore, A[i].ns, A[i].costo)
fscanf(f, "%s %d %d", A[i].costruttore, &A[i].ns, &A[i].costo)
不要使用不带宽度的“%s”
使用宽度小于数组计数的宽度 1。
char costruttore[20];
...
// fscanf(f, "%s %d %d", A[i].costruttore, ...
fscanf(f, "%19s %d %d", A[i].costruttore, ...
不要与EOF
进行比较
fscanf(f, "%s %d %d"...
可以返回(可能是 0)。与其针对 1 个不需要的值进行测试,不如与期望的结果进行比较。EOF, 1, 2, 3
// while (fscanf(f, "%s %d %d", A[i].costruttore, A[i].ns, A[i].costo) != EOF)
while (fscanf(f, "%s %d %d", A[i].costruttore, A[i].ns, A[i].costo) == 3)
评论
scanf
while (fscanf(...) == 3)
&
costruttore
char costruttore[20];
&