gpt4 book ai didi

C fgets() 只处理最后一行

转载 作者:太空宇宙 更新时间:2023-11-04 08:45:51 24 4
gpt4 key购买 nike

我正在尝试编写一个接受 .txt 文件的程序,读取所有行,然后将每个单词存储到 BST 中。然后我执行中序遍历以按字母顺序打印单词。如果文本文件仅包含 1 行,该程序将完美运行,但如果文本文件超过 1 行,则会出现意外结果。

例子:文本文件:

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,当在 while 循环中第二次调用 fgets 时,BST 的根被更改并覆盖。任何建议将不胜感激。

编辑:

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;
}

最佳答案

你需要在你的 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() 将覆盖此数组的内容。

关于C fgets() 只处理最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21691113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com