无法从文件读取数据到链接列表

问题描述 投票:-3回答:1

我正在尝试使用以下功能从文本文件读取数据,但是程序在while循环中崩溃:

void getdata(int counter) {
    int i = 0;
    user_t* temp = NULL, * ptr = NULL;
    temp = (user_t*)malloc(sizeof(user_t));
    FILE* fp;
    fp = fopen("data.txt", "r");
    int id = 0;
    int prof_obj = 0;
    int academics = 0;
    int hobby = 0;
    float salary =0 ;
    char name = "";
    char birth_place = ""; 
    char work_place= "";
    printf("1");
    while (!feof(fp)) {
        fscanf(fp, "%d %s %s %s %d %d %d %f", id, name, birth_place, work_place, prof_obj, academics, hobby, salary);//this is the line the program is crashing
        printf("%d", id);
        printf("%s", name);
        printf("%f", salary);
        printf("2");
        temp->id = id;
        strcpy(temp->name, name);
        temp->academics = academics;
        temp->hobby = hobby;
        strcpy(temp->work_place, work_place);
        temp->prof_obj = prof_obj;
        temp->salary = salary;
        strcpy(temp->birth_place, birth_place);
        temp->prox = NULL;
        if (start == NULL) {
            start = temp;
        }
        else {
            ptr = start;
            while (ptr->prox != NULL) {
                ptr = ptr->prox;
            }
            ptr->prox = temp;
        }
    }


}

我尝试使用'&',然后将其删除,但结果始终相同

c
1个回答
0
投票

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

首先,我们不知道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%s%d%d%d%d%f”,&temp-> id, temp->名称,temp->出生地点,temp->工作地点,&temp-> prof_obj,&temp-> academics,&temp->兴趣爱好和&temp->薪水);”(请注意,这是假设您已经解决了有关结构。

© www.soinside.com 2019 - 2024. All rights reserved.