【发布时间】:2021-05-11 23:06:51
【问题描述】:
这是我的 C 代码。首先,我创建了结构数据,然后读取了一个二进制文件,但是我的 fscanf 函数无法正常工作。我遇到了分段错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DATA_FILE "records.dat"
struct record
{
char name[64];
char surname[64];
char gender;
char email[32];
char phone_number[16];
char address[32];
char level_of_education[8];
unsigned int income_level;
unsigned int expenditure;
char currency_unit[16];
char currentModd[32];
float height;
unsigned int weight;
};
typedef struct record myrecord;
int main()
{
myrecord rItem;
FILE *fp;
struct record Myrecord;
if ((fp = fopen(DATA_FILE, "r")) != NULL)
{
fscanf(fp, "%s %s %s %s %s %s %s %d %d %s %s %f %d\n", &rItem.name, &rItem.surname, &rItem.gender, &rItem.email,
&rItem.phone_number, &rItem.address, &rItem.level_of_education, &rItem.income_level, &rItem.expenditure,
&rItem.currency_unit, &rItem.currentModd, &rItem.height, &rItem.weight
);
printf("doneeee");
}
else
{
printf("errorrrr ");
}
}
我的输出是这样的:
分段错误
[Done] 在 0.17 秒内以 code=139 退出
【问题讨论】:
-
您不能使用
%s格式说明符来读取 singlechar变量,就像您尝试使用&rItem.gender参数一样。不过,不确定这是否是唯一的问题,因为您谈到读取“二进制文件”,但fscanf用于 text 模式输入。修复取决于您希望gender字段是什么:单个字符(然后使用%c)或以null 结尾的字符串(然后它需要是char的数组,与其他字段一样)。 -
从数组分配中删除
&。您不需要为已经是指针的内容传递指针。 -
另外,将
%u用于无符号 整数-%d用于有符号 参数。 -
永远不要使用
%s。始终添加最大字段宽度,该宽度最多比将写入的缓冲区大小小 1。例如fscanf(fp,"%63s %63s ...当您认为gender的大小为1 时,您可能会想使用格式字符串%0s,这应该表明有问题。 -
您还应该检查 f/s scanf 系列函数的返回值。
标签: c