首页 > 解决方案 > 无法将文件中的数据读入链表

问题描述

好的,我已经设法解决了我的问题,感谢所有回答的人。结果在这段代码中我在错误的地方分配内存,我应该在'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;
}

标签: c

解决方案


您的代码存在一些明显的问题。

首先,我们不知道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];会做 - 但显然你需要比你最大的预期名字更大的尺寸。

下一个:您永远不会检查mallocfopen工作 - 两者都可能失败。当然 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 的第一个问题。


推荐阅读