c - 无法将文件中的数据读入链表
问题描述
好的,我已经设法解决了我的问题,感谢所有回答的人。结果在这段代码中我在错误的地方分配内存,我应该在'for'循环内分配,这样数据就不会被覆盖
void getdata (int counter){
int i = 0;
user_t* temp = NULL, * ptr = NULL;
//temp = (user_t*)malloc(sizeof(user_t)); this is what I was doing
FILE *varfile;
varfile = fopen ("data.txt", "r");
if (varfile==NULL) {
printf("Error");
return;
}
else {
for (i = 0; i < counter; i++){
temp = (user_t*)malloc(sizeof(user_t)); //and this is where I should be allocating
fscanf (varfile, "%d %s %s %s %d %d %d %f", &temp->id, temp->name, temp->birth_place, temp->work_place, &temp->prof_obj, &temp->academics, &temp->hobby, &temp->salary);
temp->prox = NULL;
if (start == NULL) {
start = temp;
}
else {
ptr = start;
while (ptr->prox != NULL) {
ptr = ptr->prox;
}
ptr->prox = temp;
}
}
}
fclose (varfile);
return;
}
解决方案
您的代码存在一些明显的问题。
首先,我们不知道user_t
长什么样。如果是这样
typedef struct user {
...
char* name;
...
} user_t;
然后temp = (user_t*)malloc(sizeof(user_t));
实际上并没有为您提供任何名称空间 - 您需要另一个 malloc (或使用strdup
代替strcpy
)或将空间直接放入结构中:
typedef struct user {
...
char name[64];
...
} user_t;
Next: 这样的行甚至不应该编译:char name = "";
因为类型错误。该变量是 char 类型,但您正在为其分配一个字符串。char* name = "";
会编译但仍然是错误的。您正在使用这些变量作为缓冲区来读取字符串。您需要空间来存储字符串。char name[64];
会做 - 但显然你需要比你最大的预期名字更大的尺寸。
下一个:您永远不会检查malloc
或fopen
工作 - 两者都可能失败。当然 malloc 不太可能失败,但打开的文件可能 - 在任何一个失败时继续是未定义的行为。
下一步:scanf
需要读取到的地址,所以应该像fscanf(fp, "%d %s %s %s %d %d %d %f", &id, name, birth_place, work_place, &prof_obj, &academics, &hobby, &salary);
注意字符串缓冲区已经是地址,所以你不需要它们上的&符号。
您可以通过直接阅读“temp”来避免使用临时变量和字符串副本:(fscanf(fp, "%d %s %s %s %d %d %d %f", &temp->id, temp->name, temp->birth_place, temp->work_place, &temp->prof_obj, &temp->academics, &temp->hobby, &temp->salary);
请注意,这假设您已经解决了关于 struct.xml 的第一个问题。
推荐阅读
- javascript - 在 Chrome 扩展中使用 Google API 电子表格 JS 删除值
- python - 隐藏(或不显示)mplfinance 中的图
- sql - 如何在 SQL SERVER 2016+ 中生成 SHA-3(256) 哈希
- node.js - 如何在 Github 操作中设置 sendgrid 邮件?
- r - “无法分配大小向量......”即使 memory.limit() 和 memory.size() 更高,也会出现错误
- html - 避免 html 选择值更改模糊
- python - Python 和线程:为什么在锁定区域之外提取计算会加速代码?
- android - 设置“数字”并输入禁止字符时,EditText 隐藏错误消息
- reporting-services - 基于多参数的SSRS填充颜色表达式
- database - Kubernetes 持久化卷:主机路径与本地和数据持久化