简体   繁体   English

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

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

I am trying to read words from a file. 我正在尝试从文件中读取单词。 The file is a txt and contain some words.In my text i have around 10 words. 该文件是txt文件,包含一些单词。在我的文字中,我大约有10个单词。 Evertime although i run the code i only get the first word. 每次,尽管我运行代码,但我只会得到第一个单词。 What am i doing wrong? 我究竟做错了什么?

#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)
}

Do i need perhaps to add all of them in one loop? 我是否需要将所有这些都添加到一个循环中? and if yes will i have to use EOF ? 如果是的话,我将不得不使用EOF吗?

Write you loop like this - 像这样写你的循环-

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

Also , you print word in function itself then why do you return it from function and when called in main you don't assign it to anything , you just write - 另外,您可以在函数本身中打印word ,然后为什么要从函数中return word ,而在main调用时却没有将其分配给任何内容,只需编写-

 getword(a);

in main . main Then why not declare function as void ? 那为什么不将函数声明为void呢?

The loop could be written like this: 循环可以这样写:

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

What is the purpose of using firstTime ? 使用firstTime的目的是firstTime

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

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