2013-12-12 86 views
0

我(一如既往)在寫入和讀取鏈接列表時遇到了一些麻煩。 它被保存到二進制文件的事實使我困惑。 我試圖編寫一個簡單的程序,只有一個簡單的結構與兩個變量,並寫入並讀取到磁盤,只是爲了檢查我是否濫用fread()fwrite()。但是,我沒有。該計劃運行順利。 當我開始將指針和節點添加到鏈接列表時,麻煩就開始了。我檢查了stackoverflow.com,cplusplus.com,cprograming.com,並且從我所看到的,我的程序沒有錯。試過調試,什麼都沒有。編譯器根本沒有抱怨。寫入和讀取鏈接列表

我在下面包含的源代碼非常簡單:包含一個帶有兩個變量的結構,名稱和代碼就像一個客戶端控件。代碼由程序自動提供,用戶輸入名稱。程序應該保存數據,並繼續。但是,它不會超過fir->sacode = 1分配。 任何提示將不勝感激。

#include <stdio.h> 

void save(void); 
int load(void); 

struct solic { 
    char name[10]; 
    int sacode; 
    struct solic *next; 
}; 

struct solic *cur, *fir; 
int sacode = 1; 

int main() 
{ 
    if(load() == 0) 
     printf("Load Successful!\n"); 

    char cho1; 
    fir->sacode = 1; 
    cur=fir; 
    while(1){ 
     cur->sacode = sacode; 
     printf("Client code is %04d",cur->sacode); 
     printf("Enter client name: "); 
     scanf("%s",cur->name); 
     save(); 
     printf("Saved!\n"); 
     printf("Press '1' to enter another client, or 'Enter' to save and exit.\n"); 
     scanf("%c",&cho1); 
     if(cho1 == '1') 
     { 
      cur->next = (struct solic *)malloc(sizeof(struct solic)); 
      cur = cur->next; 
      sacode++; 
      cur->sacode = sacode; 
      continue; 
     } 
     else if(cho1 == '\r'); 
      break; 
    } 

    return(0); 
} 

void save(void) 
{ 
    FILE *pFile; 
    pFile = fopen("db.dat","w"); 
    while(cur != NULL) 
    { 
     fwrite(cur->name,sizeof(cur->name),1,pFile); 
     fwrite(&cur->sacode,sizeof(int),1,pFile); 
     cur = cur->next; 
    } 
    fclose(pFile); 
} 

int load(void) 
{ 
    int size; 
    char buffer[10]; 

    FILE *pFile; 
    pFile = fopen("db.dat","r"); 
    if(pFile == NULL) 
     return(1); 

    size = fseek(pFile,0,SEEK_END); 
    rewind(pFile); 
    cur = fir; 

    while(size >= ftell(pFile)) 
    { 
     fread(cur->name,sizeof(cur->name),1,pFile); 
     fread(buffer,sizeof(int),1,pFile); 
     cur->sacode = atoi(buffer); 
     sacode++; 
     cur->next = (struct solic *)malloc(sizeof(struct solic)); 
     cur = cur->next; 
    } 
    cur->next = NULL; 
    return(0); 
} 

回答

2
  1. 你第一次運行這個程序,load()將失敗,因爲沒有數據。這意味着fir將不會被初始化,因此fir->sacode = 1將嘗試更新內存中的某個隨機位置。在fir中存儲任何內容之前,您需要爲malloc()分配一個新節點。

  2. 您的save()函數每次運行時都會寫入一個新的db.dat文件,從cur指針開始。但每次調用時,cur都指向列表中的最後一個元素。您將需要打開該文件進行追加,因此它不會寫入任何已經存在的數據,或者循環遍歷整個列表。

+0

@rrrty謝謝你的答案!所以在理論上,可以用''fir =(struct solic *)malloc(sizeof(struct solic));''將節點分配給'fir''來解決,對嗎? 2.這可以通過將'cur''分配給''fir''來解決,然後在列表中循環。 –

+0

準確。請注意,在這裏傳遞'malloc()'的返回值是非常不受歡迎的,所以我建議你使用'fir = malloc(sizeof(struct solic))',以避免被爭論的人爭執。 :-) –