2014-02-11 165 views
0

我正在嘗試編寫一個程序,它接受.txt文件,讀取所有行,然後將每個單詞存儲到BST中。然後我執行一個inorder遍歷來按字母順序打印這些單詞。如果文本文件僅包含1行,該程序完美工作,但如果文本文件包含多於1行,則會出現意外結果。C fgets()只處理最後一行

例如:文本文件:

first line 
second line 

只輸出:

line 
second 

完全失去了文本文件的第一行。

我的主要方法是:

#define MAX_STR_LEN 1024 
int main(int argc, char** argv) 
{ 
    FILE *fptr; 
    fptr = fopen(argv[1], "r"); 

    if(fptr == NULL) 
    { 
    printf("Error. Could not open file.\n"); 
    exit(1); 
    } 

    char line[MAX_STR_LEN]; 
    char* tok; 
    struct BSTnode* theRoot; 
    int isRoot = 1; 

    while(fgets(line, MAX_STR_LEN, fptr) != NULL) 
    { 
    tok = strtok(line, " \n"); 


    while(tok != NULL) 
    { 
     if(isRoot == 1) 
     { 
     theRoot = createNode(tok); //creates the root for the BST 
     isRoot = 0; 
     } 
     else 
     { 
      processStr(&theRoot, tok); //places a new word into the BST 
     } 

     tok = strtok(NULL, " \n"); 
    } 

    } 

    inorder(theRoot); //prints words alphabetically 
    fclose(fptr); 
    return 0; 
} 

我踩通過與GDB當與fgets被要求在while循環的第二次,BST的theRoot改變和覆蓋。任何意見,將不勝感激。

編輯:

struct BSTnode* createNode(char* word) 
{ 
    struct BSTnode* temp = malloc(sizeof(struct BSTnode)); 
    temp->word = word; 
    temp->left = NULL; 
    temp->right = NULL; 
    return temp; 
} 

void processStr(struct BSTnode** root, char* word) 
{ 
    struct BSTnode** node = search(root, word); 
    if (*node == NULL) { 
     *node = createNode(word); 
    } 
} 

struct BSTnode** search(struct BSTnode** root, char* word) { 
    struct BSTnode** node = root; 
    while (*node != NULL) { 
     int compare = strcasecmp(word, (*node)->word); 
     if (compare < 0) 
      node = &(*node)->left; 
     else if (compare > 0) 
      node = &(*node)->right; 
     else 
      break; 
    } 
    return node; 
} 
+0

在'createNode()'和'processStr()'中,你複製了這個單詞還是隻存儲了一個指針? –

+0

這兩個函數都以char *作爲參數。結構BSTnode包含一個char *字。在createNode(char * word)中分配一個新節點,然後node-> word設置爲word(參數)。 – WinterStar

+0

請更新您的問題,並在其中包含您的'createNode()'和'processStr()'。 –

回答

2

你需要複製這個詞在你createNode(),你可以試試:

struct BSTnode* createNode(char* word) 
{ 
    struct BSTnode* temp = malloc(sizeof(struct BSTnode)); 
    temp->word = malloc(strlen(word) + 1); 
    strcpy(temp->word, word); 
    temp->left = NULL; 
    temp->right = NULL; 
    return temp; 
} 

在你createNode()word是一個指向子在line,另一個調用fgets()將覆蓋此數組的內容。