从文件中读取单词到简单的链表

我需要编写一个程序来读取文件,然后将这些单词保存到链表中以供进一步使用。 我决定使用fgetc逐个字符地读取文本,然后每次检测到换行符( '\n' )或空格( ' ' )时将全部保存到列表中,表示一个单词。 对不起,我是文件指针的新手,这是我到目前为止所得到的:

 struct list { //global char string[30]; struct list *next; }; int main(void) { FILE *filePtr; char file[] = "text.txt"; char tempStr[30]; list *curr, *header; char c; int i = 0; curr = NULL; header = NULL; if((filePtr = fopen(file, "r")) == NULL) { printf("\nError opening file!"); getchar(); exit(101); } printf("\nFile is opened for reading.\n"); while(!EOF) { while((c = fgetc(filePtr) != ' ') && (c = fgetc(filePtr) != '\n')) { curr = (list*)malloc(sizeof(list)); //c = fgetc(filePtr); tempStr[i] = fgetc(filePtr); i++; } tempStr[i] = '\0'; strcpy(curr->string, tempStr); curr->next = header; header = curr; i = 0; } while(curr!=NULL) { printf("%s - ", curr->string); //This will not print. curr = curr->next; } if(fclose(filePtr) == EOF) { printf("\nError closing file!"); getchar(); exit(102); } printf("\nFile is closed.\n"); getchar(); getchar(); } 

如果是文本文件:

 have a nice day 

期望的输出:

 have - a - nice - day 

但是,除了文件打开和关闭之外,我无法打印出任何内容。

谢谢。

EOF值为-1 ,这是stdio.h定义的系统宏。 文件读取API( fgetcfreadfscanf )一旦到达文件末尾就会返回-1。 所以在你的程序中你有while(!EOF)这将永远是假的,因为-1总是0. -1将用2的补码表示,所以该变量的所有位都是1.(如果int大小是2, -1将在int变量中存储为0xFFFF )。

使用以下示例代码。

 while(EOF != (c = fgetc(filePtr))) { if ((c == ' ') || (c == '\n')) { if (i == 0) { continue; } tempStr[i] = '\0'; i = 0; //here do your linklist node creation and insertion operation continue; } tempStr[i] = c; i++; } 
 while(!EOF) { 

这是一个始终为假的常量条件,因此您永远不会读取任何内容。

您的代码还有其他问题,例如

 curr = (list*)malloc(sizeof(list)); 

在循环中但在循环外使用curr。

你应该用你用来读取文件的任何函数替换while条件 – 你确定fgets不是比这更有效吗?

IE将字符串读入比预期更大的缓冲区,然后将其复制到适当大小的缓冲区并将其附加到节点。

  • 这总是错误的:

     while(!EOF) 
  • 查看内存分配代码。

     curr = (list*)malloc(sizeof(list)) 
  • 文件末尾的文件可能没有换行符。

     while((c = fgetc(filePtr) != ' ') && (c = fgetc(filePtr) != '\n')) 

扰流板:

 #include  #include  #include  struct list { struct list *next; char string[30]; }; int main(void) { FILE *fp; char file[] = "llist4.c"; /* in C you CANNOT omit the "struct keyword" from a declaration or definition. */ struct list *head=NULL, **pp= &head; int ch; /* getc() returns an int */ size_t len ; char buff[30]; fp = fopen(file, "r"); if (!fp) { fprintf(stderr, "\nError opening file!"); exit(EXIT_FAILURE); } printf("\nFile has been opened for reading.\n"); for (len=0; len < sizeof buff; ) { ch = fgetc(fp); if (ch == EOF && !len) break; if (ch == ' ' || ch == '\n' || ch == EOF) { if (!len) continue; buff[len] = '\0'; *pp = malloc(sizeof **pp); if (!*pp) break; strcpy((*pp)->string, buff); (*pp)->next = NULL; pp = &(*pp)->next ; len=0; continue; } buff[len++] = ch; } if (len) { fprintf(stderr, "\nWord was too large, or out of memory\n"); } for( ;head; head= head->next) { printf("%s - ", head->string); } if (fclose(fp) == EOF) { fprintf(stderr, "\nError closing file!\n"); exit(EXIT_FAILURE); } printf("\nFile has been closed.\n"); exit(EXIT_SUCCESS); }