如何将字符串文件读入链表? (C)

How do you read a file of strings into a linked list? (C)

我的结构定义如下:

typedef struct node {
  char * word;
  int wordLength;
  int level;
  struct node * parent;
  struct node * next;
}Node;

我正在尝试创建上面结构的链接列表,其中 "word" 是一个字符串,它是从文件中读取的。下面是我用来创建列表的函数。似乎工作正常,并打印出文字,但是,当我尝试在 main() 中打印出来时,它没有打印任何内容。

void GetWords(char * dictionary, Node * Word, Node * Start)
{
  FILE *fp;
  char * currentWord = (char *)malloc(sizeof(char));
  fp = fopen(dictionary, "r");
  ErrorCheckFile(fp);
  if(fscanf(fp, "%s", currentWord) == 1){
    Start = Word = AllocateWords(currentWord);
  }

  while((fscanf(fp, "%s", currentWord)) != EOF){
    Word->next = AllocateWords(currentWord);
    Word = Word->next;
    printf("%s: %d\n", Word->word, Word->wordLength);
  }



  fclose(fp);
}

我需要 return 到列表的开头吗?如果是这样,我该怎么做?在这个函数中,我有 "Start" 指向文件中的第一个单词,我需要这个吗? 我正在尝试打印它们,只是为了确定文件是否正确存储在列表中。

我的 main() 函数是:

int main(int argc, char ** argv)
{
  Node * Word = (Node *)malloc(sizeof(Node));
  Node * Start = (Node *)malloc(sizeof(Node));
  GetWords(argv[1], Word, &Start);


  printf("Start: %s\n", Start->word);
  printf("Word: %s\n", Word->word);
  while(Word->next != NULL){
    printf("%s\n", Word->word);
  }

  return 0;
}

打印语句只是在那里检查列表是否正在打印。就目前而言,Start->word 正在打印文件中的最后一个单词,Word->word 正在打印(空)并且 while 循环根本没有执行。

我的AllocateWords()函数如下:

Node * AllocateWords(char * string)
{
  Node * p;
  p = (Node *)malloc(sizeof(Node));
  if(p == NULL){
    fprintf(stderr, "ERROR: Cannot allocate space...\n\n");
    exit(1);
  }
  p->word = string;
  p->wordLength = strlen(p->word);
  p->parent = NULL;
  p->next = NULL;
  return p;
}

Start 指针使用按引用调用而不是按值调用。

main() 函数:

Node * Start

GetWords(..., &Start)

 void GetWords(char * dictionary, Node * Word, Node ** Start)
 {

  ....
  *Start = Word = AllocateWords(currentWord);
  ....

您还需要修正 currentWord 的大小。如果最大 字长为255个字符,使用:

char * currentWord = (char *)malloc(256*sizeof(char));
...
if(fscanf(fp, "%255s", currentWord) == 1){
...
while((fscanf(fp, "%255s", currentWord)) != EOF){

您还需要修复 main() 函数。 您不需要分配当前字指针 WordStart 节点指针。

...
Node * Word = (Node *) NULL;
Node * Start = (Node *) NULL;
GetWords(argv[1], Word, &Start);

printf("Start: %s\n", Start->word);
Word = Start;
while(Word->next){           // identical to while(World->next!=NULL){      
  Word=Word->next;
  printf("%s\n", Word->word);
}