[英]Can't read data from file into a linked list
好的,我已经设法解决了我的问题,感谢所有回答的人。 结果在这段代码中我将 memory 分配在错误的位置,我应该在“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;
下一个:这样的行甚至不应该编译: 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 的第一个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.