简体   繁体   中英

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. 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 ?

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 -

 getword(a);

in main . Then why not declare function as 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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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