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

时间:2012-06-23 09:30:16

标签: c pointers file-io linked-list

我需要编写一个程序来读取文件,然后将这些单词保存到链表中以供进一步使用。我决定使用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

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

感谢。

5 个答案:

答案 0 :(得分:1)

EOF的值为-1,这是stdio.h中定义的系统宏。文件读取API(fgetcfreadfscanf)一旦到达文件末尾将返回-1。因此,在您的程序中,while(!EOF)这将始终为false,因为NOT的{​​{1}}始终为0. -1将以2的补码表示,因此该变量的所有位将为1.(如果-1的大小为2,则int-1存储为0xFFFF变量中的int

使用以下示例代码。

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

答案 1 :(得分:0)

  • 这总是错误的:

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

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

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

答案 2 :(得分:0)

while(!EOF) {

这是一个始终为假的常量条件,所以你永远不会读任何东西。

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

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

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

答案 3 :(得分:0)

您应该使用您正在使用的任何函数来替换while条件来读取文件 - 您确定fgets的效率并不比这更高效吗?

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

答案 4 :(得分:0)

扰流:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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);
}
相关问题