C fgets()仅处理最后一行
我正在尝试编写一个程序,它接收一个.txt文件,读取所有行,然后将每个单词存储到一个BST中。然后执行顺序遍历,以按字母顺序打印单词。如果文本文件仅包含一行,则程序可以正常运行,但如果文本文件包含多行,则会出现意外结果 示例:文本文件:C fgets()仅处理最后一行,c,file,binary-search-tree,fgets,C,File,Binary Search Tree,Fgets,我正在尝试编写一个程序,它接收一个.txt文件,读取所有行,然后将每个单词存储到一个BST中。然后执行顺序遍历,以按字母顺序打印单词。如果文本文件仅包含一行,则程序可以正常运行,但如果文本文件包含多行,则会出现意外结果 示例:文本文件: first line second line 仅输出: line second 完全丢失文本文件的第一行 我的主要方法是: #define MAX_STR_LEN 1024 int main(int argc, char** argv) { FILE *
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->left=NULL;
temp->right=NULL;
返回温度;
}
void processStr(结构BSTnode**root,char*word)
{
结构BSTnode**node=搜索(根,字);
如果(*节点==NULL){
*node=createNode(word);
}
}
结构BSTnode**搜索(结构BSTnode**根,字符*字){
结构节点**节点=根;
while(*node!=NULL){
int compare=strcasecmp(word,(*node)->word);
如果(比较<0)
节点=&(*节点)->左侧;
否则如果(比较>0)
节点=&(*节点)->右侧;
其他的
打破
}
返回节点;
}
您需要复制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
是指向行中的子字符串的指针,对fgets()
的另一个调用将覆盖此数组的内容。在createNode()
和processStr()
中,您是复制了这个单词还是只存储了指向它的指针?这两个函数都以char*作为参数。struct BSTnode包含一个char*字。在createNode(char*word)中,分配一个新节点,然后将node->word设置为word(参数)。请更新您的问题,并将您的createNode()
和processStr()
包含在其中。
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;
}