繁体   English   中英

从文件中读取单词无法正常工作

[英]Reading words from a file doesn't work as supposed to

我正在尝试从文件中读取单词。 该文件是txt文件,包含一些单词。在我的文字中,我大约有10个单词。 每次,尽管我运行代码,但我只会得到第一个单词。 我究竟做错了什么?

#include<stdio.h>
#include<stdlib.h>
#define WORDLEN 30

/* Given the name of a file, read and return the next word from it, 
or NULL if there are no more words */

char *getWord(char *filename)  {
    char formatstr[15], *word;
    static FILE *input;
    static int firstTime = 1;
    if (firstTime) { 
        input = fopen(filename, "r");
        if (input == NULL) {
            printf("ERROR: Could not open file \"%s\"\n", filename);
            exit(1);
        }
        firstTime = 0;
    }
    word = (char*)malloc(sizeof(char)*WORDLEN);
    if (word == NULL) {
        printf("ERROR: Memory allocation error in getWord\n");
        exit(1);
    }
    sprintf(formatstr, "%%%ds", WORDLEN-1);
    fscanf(input, formatstr, word);
    if (feof(input)) {
        fclose(input);
        firstTime = 1;
        return NULL;
    }


    printf("%s", word)
    return word;
}

int main()
{
    char a[] = "tinydict.txt";
    getword(a)
}

我是否需要将所有这些都添加到一个循环中? 如果是的话,我将不得不使用EOF吗?

像这样写你的循环-

 while(fscanf(input, formatstr, word)==1){   // this will read until fscanf is successful
   printf("%s", word);
 }

另外,您可以在函数本身中打印word ,然后为什么要从函数中return word ,而在main调用时却没有将其分配给任何内容,只需编写-

 getword(a);

main 那为什么不将函数声明为void呢?

循环可以这样写:

while (!feof(input)){
    if (fscanf(input, formatstr, word) == 1){
        printf("%s", word);
    }
}

使用firstTime的目的是firstTime

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM