簡體   English   中英

無法將文件中的數據讀入鏈表

[英]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]; 會做 - 但顯然你需要比你最大的預期名字更大的尺寸。

下一步:您永遠不會檢查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 的第一個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM