2014-04-03 43 views
0

我正在研究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 

這似乎繼續一次周圍循環和使用更多。作爲單詞,然後打印出要讀入的最後一個意思。關於如何解決這個問題的任何想法?此外,如果有更有效的方式做我正在做的事情,那麼也讓我知道。

回答

0

快速回答:變化:

if (strcmp(word, ".") == 0) { 
     break; 
    } 
    sscanf(dbuffer, "%s %[^\n]",word, meaning); 

到:

sscanf(dbuffer, "%s %[^\n]",word, meaning); 
    if (strcmp(word, ".") == 0) { 
     break; 
    } 

此外,它是很好的做法,檢查的sscanf返回值這裏是2,否則meaning是沒有意義的,而且會可能具有以前的值,如輸出所示。如果它不是2,並且word不是".",那麼您的輸入文件有語法錯誤,您應該例如退出並顯示錯誤消息。

而且,在您的原始代碼中,word在首次檢查時未初始化。

+0

*** ***編輯:它是很好的做法,調用'fclose(file);' –

0
sscanf(dbuffer, "%s %[^\n]",word, meaning); 
    printf("%s\n", word); 
    printf("%s\n", meaning); 

您掃描的文字和打印您檢查之前,如果它是"."

2

你檢查worddbuffer提取之前。它仍然具有循環最後一次的價值。

自上線可能會或可能不包括換行,最簡單的出路就是繼續之前檢查dbuffer對兩個版本:

while((fgets(dbuffer, sizeof(dbuffer), file))) { 
    if ((strcmp(dbuffer, ".") == 0) || strcmp(dbuffer, ".\n") == 0) { 
    break; 
    } 

    // ... 
} 
相關問題