2016-11-06 35 views
-2
#include<stdio.h> 
struct Node{ 
    char *name; 
    int time; 
    int sec; 
    int x; 
    int y; 
    struct Node *next; 
}; 
int main(){ 
    FILE *file; 
    int index; 
    struct Node *data=malloc(sizeof(struct Node)); 
    struct Node *tmp=data,*tmp2=data; 
    int enter; 

    file=fopen("data.txt","r"); 

    if(file==NULL){ 
     printf("File was not opened!\n"); 
     return 0; 
    } 

    while(!feof(file)){ 
     tmp=malloc(sizeof(struct Node)); 
     fscanf(file,"%d",&index); 
     fscanf(file,"%d",&tmp->time); 
     fscanf(file,"%d",&tmp->sec); 
     fscanf(file,"%d",&tmp->x); 
     fscanf(file,"%d",&tmp->y); 
     fscanf(file,"%s",tmp->name); 
     fscanf(file,"%'\0",&enter); 
     tmp->next=NULL; 
     tmp=tmp->next; 
    } 
    fclose(file); 
    while(tmp2 != NULL){ 
     printf("file:%d\t%d\t%d\t%d\t%s\n",tmp2->timestamp,tmp2->sec,tmp2->pointx,tmp2->pointy,tmp2->name); 
     tmp2=tmp2->next; 
    } 
    return 0; 
} 

需要一些幫助來從文件讀取數據並將它們寫入鏈接列表,然後將鏈接列表打印到secreen.But然後停止工作後immedately我啓動program.In文件數據是這樣的:讀取文件中的數據並將其寫入鏈接列表

  • 1 28000 41 29 50 BBB
  • 2 29000 91 19 60 CCC
  • 3 30000 23 77 92 DDD
  • 4 30000 37 62 65 eee
  • 5 31000 14 45 48 FFF

(它們之間有標籤)

我讀了很多問題,但他們的答案並沒有幫助我,我覺得我缺少一個點的地方,但我看不到問題。是關於直接讀取鏈接列表還是其他內容?感謝幫助。 //我正在看我的代碼againt感謝您的幫助**(編輯)

+1

這個''%'\ 0「'和這個''%'」'完全一樣,你應該怎麼做?如果你閱讀文檔,你認爲它會做什麼? –

+0

「..它給出了錯誤信息..「請**從來沒有讓我們猜猜你得到了什麼具體的錯誤 – usr2564301

+0

順便說一句,你還在學習,*你應該閱讀很多*和實驗。請注意,你需要幾天的全職工作在這個家庭作業 –

回答

3

name字段是一個指針,但你永遠不會分配它。所以

fscanf(file,"%s",tmp->name); 

undefined behavior。你真的應該是very scared。花幾個小時閱讀Lattner的博客:what every C programmer should know about undefined behavior

也許你可能使用getline(3)如果在POSIX系統上讀取一行,或者使用。

順便說一句,當我編譯您的代碼與所有警告&調試信息(與gcc -Wall -g如果使用GCC)我收到許多錯誤和警告。你應該改進你的代碼,直到你沒有任何警告。然後你應該使用調試器(gdb)來查找許多其他的錯誤。你將能夠一步一步地運行你的bug程序並查詢一些變量。您應該在黑板上(或紙上)畫出您認爲是運行程序的process的內存(包括堆)的模型和形狀。你會發現幾個錯誤。詳細瞭解C dynamic memory allocationvirtual address space

而且,#include <stdlib.h>使用malloc(3)

時,請仔細閱讀所使用,尤其是對於fscanf每個函數的文檔是必需的。

請注意,您忘記處理malloc的故障;並且我還建議在故障情況下使用perror(3)。所以至少用替換爲

tmp = malloc(sizeof(struct Node)); 
if (!tmp) { perror("malloc Node"); exit(EXIT_FAILURE); }; 

PS。我希望你不要指望我們做你的功課。你的程序非常麻煩,但你會通過自己找到這些錯誤來學到很多東西。詢問別人會適得其反。

相關問題