[英]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.