[問題]將 txt file讀進 BST
首先我要讀的txt file內容大概是
Cheetah; Acinonyx; Felidae; Carnivora; Mammalia;
Giraffe; Giraffa; Giraffidae; Artiodactyla; Mammalia;
.
.
.
從左至右依序是 normal name->genus->family->order->class 有30組
這是我的結構
typedef struct
{
char*animal;
struct nodetag*ptrfields;
}ANIMAL;
typedef struct nodetag
{
char*genus;
char*family;
char*order;
char*class;
}NODE;
主要是要將內容讀到BST裡面
void load(BST_TREE*list)
{
//local definition
FILE*fptr;
ANIMAL*data;
NODE*ptrnode;
char buffer[100];
char ptrgenus[20];
char ptrfamily[20];
char ptrorder[20];
char ptrclass[20];
//statement
fptr=fopen("input_animals.txt","r");
if(fptr==NULL)
{
printf("error opening the file");
return 0;
}
while(fgets(buffer,sizeof(buffer),fptr))
{
sscanf(buffer,"%s;%s;%s;%s;%s",ptranimal,
ptrgenus,ptrfamily,ptrorder,ptrclass);
//用buffer讀,請問中間的分號這樣可以在讀的時候去掉嗎?
//allocate memory
data=(ANIMAL*)malloc(sizeof(ANIMAL));
if(!data)
printf("not enough memory\n"),exit(100);
data->animal=(char*)malloc(strlen(ptranimal)+1,sizeof(char));
if(!data->animal)
printf("not enough memory\n"),exit(110);
ptrnode=(NODE*)malloc(sizeof(NODE));
if(!data)
printf("not enough memory\n"),exit(120);
ptrnode->genus=(char*)malloc(strlen(ptrgenus)+1,sizeof(char));
if(!ptrnode->genus)
printf("not enough memory\n"),exit(130);
ptrnode->family=(char*)malloc(strlen(ptrfamily)+1,sizeof(char));
if(!ptrnode->family)
printf("not enough memory\n"),exit(200);
ptrnode->order=(char*)malloc(strlen(ptrorder)+1,sizeof(char));
if(!ptrnode->order)
printf("not enough memory\n"),exit(201);
ptrnode->class=(char*)malloc(strlen(ptrclass)+1,sizeof(char));
if(!ptrnode->class)
printf("not enough memory\n"),exit(300);
//將讀到的字串assign到對應的pointer裡
strcpy(data->animal=ptranimal);
strcpy(ptrnode->genus,ptrgenus);
strcpy(ptrnode->family,ptrfamily);
strcpy(ptrnode->order,ptrorder);
strcpy(ptrnode->class,ptrclass);
data->ptrfields=ptrnode; //不確定這裡能不能將ptrnode assign到 ptrfields裡
BST_Insert(list,data);
//list是BST,在read file前就先創好了
return;
}
因為file讀不進去 後面就不用跑了.... 自己又看不出來哪裡有錯
所以自私的希望有人可以幫我看一下順便提點一下 囧!
還有我每次都搞不懂exit(x)裡面的x 是怎麼來的 所以我程式裡是亂放的.....
感激不盡.....
( *[1m *[m 為色碼,可以按 Ctrl+V 預覽會顯示的顏色 ) ( 未必需要依照此格式,文章條理清楚即可 )
遇到的問題: (題意請描述清楚)
希望得到的正確結果:
程式跑出來的錯誤結果:
開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux)
有問題的code: (請善用置底文標色功能)
補充說明:
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 24.7.54.192
※ 編輯: freeinmind 來自: 24.7.54.192 (11/24 13:43)
→
11/24 14:40, , 1F
11/24 14:40, 1F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章