链接列表从文件中读取

时间:2014-09-19 21:00:51

标签: c

我有一个结构如下

struct employeeData
   {
     int EMP_ID;
     char name[20];
     int dept;
     int rank;
     int salary;

     struct employeeData *next;
   };

我创建了一个函数

void initializeList(struct employeeData *List)

我试图从

格式的文件中读取信息
12   Bob   2     1    65000
13   Sally  5   3    30000

我目前正在尝试

void initializeList(struct employeeData *List)

{

    FILE *ifp;
    ifp = fopen("empInfo.txt","r");

    while (ifp != 0)
{

    fscanf(ifp, " %d %s %d %d %d ", &List->EMP_ID, &List->name, &List->dept, &List->rank, &List->salary);

    List->next;

}

    fclose(ifp);

}

这必须是一个链接列表,我知道在某处需要Malloc但是我被卡住了。

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

typedef struct employeeData {
    int EMP_ID;
    char name[20];
    int dept;
    int rank;
    int salary;

    struct employeeData *next;
}EMP;

EMP *new_EMP(void){
    EMP *node = calloc(1, sizeof(EMP));
    if(!node){
        fprintf(stderr, "failed to create an employee.\n");
        exit(EXIT_FAILURE);
    }
    return node;
}

EMP *readf_EMP(FILE *fp){
    EMP emp = { .next = NULL };
    if(5==fscanf(fp, "%d %19s %d %d %d", &emp.EMP_ID, emp.name, &emp.dept, &emp.rank, &emp.salary)){
        EMP *node = new_EMP();
        *node = emp;
        return node;
    }
    return NULL;
}

EMP *initializeList(void){
    FILE *ifp;
    ifp = fopen("empInfo.txt","r");
    EMP *np, *head=NULL, *curr;

    while (np = readf_EMP(ifp)){
        if(!head)
            head = curr = np;
        else
            curr = curr->next = np;
    }
    fclose(ifp);
    return head;
}
相关问题