我正在研究C語言的字典實現,它要求我使用單詞和定義讀入多行文件。我可以正確地讀取文件,但不是EOF,而是一個句號。用於標記文件的結尾。我試圖阻止程序在讀取文件後立即讀取文件。但無濟於事。如何在'。'時停止讀取C中的多行文件。到達了?
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_WORD_SIZE 40
#define MAX_DESC_SIZE 200
int d_read_from_file(const char * filename){
char dbuffer[MAX_WORD_SIZE+MAX_DESC_SIZE+2];
char word[MAX_WORD_SIZE+1];
char meaning[MAX_DESC_SIZE+1];
int i = 0;
FILE *file = fopen(filename, "r");
if (file == 0)
{
printf("Could not open file\n");
return 0;
}
while((fgets(dbuffer, sizeof(dbuffer), file))) {
if (strcmp(word, ".") == 0) {
break;
}
sscanf(dbuffer, "%s %[^\n]",word, meaning);
printf("%s\n", word);
printf("%s\n", meaning);
}
return 1;
/* d_read_from_file(filename);*/
}
int main(int argc, char ** argv)
{
int i;
for (i=1; i<argc; i++)
d_read_from_file(argv[i]);
}
我知道代碼看起來有點凌亂的權利,但我只是想獲得它停止一旦它擊中。字符。
下面是輸入的例子:
computer Electronic device for processing data according to instructions
playground Area of outdoor play or recreation
plateau Land area with high, level surface
aardvark Unfriendly, nocturnal mammal native to Africa
.
和輸出我從代碼得到我已經寫了:
computer
Electronic device for processing data according to instructions
playground
Area of outdoor play or recreation
plateau
Land area with high, level surface
aardvark
Unfriendly, nocturnal mammal native to Africa
.
Unfriendly, nocturnal mammal native to Africa
這似乎繼續一次周圍循環和使用更多。作爲單詞,然後打印出要讀入的最後一個意思。關於如何解決這個問題的任何想法?此外,如果有更有效的方式做我正在做的事情,那麼也讓我知道。
*** ***編輯:它是很好的做法,調用'fclose(file);' –