2015-04-21 76 views
0

此代碼沒有讀取全文file.namely,第一個30-40不讀取該單詞。爲什麼?C中的文件讀取錯誤

字源:http://www.cs.hmc.edu/~geoff/classes/hmc.cs070.200009/homework10/simple.dict

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
FILE *fp = fopen("simple.txt","r"); 

char buf[25]; 

while (!feof(fp)) 

{ 
    fscanf(fp,"%s",buf); 
    printf(" %s\n ", buf); 

} 
fclose(fp); 
return 0; 

} 
+1

「不讀單詞」 ?咦?你的代碼跳過了第30-40行的文本? –

+1

如果你包含你的輸出將會很有幫助。 –

+3

源文件名爲「simple.dict」,此代碼嘗試讀取「simple.txt」。 – chux

回答

1

有些腥物:

  1. 檢查文件打開沒有依靠它之前失敗。
  2. 不要使用feof()這樣,它不是什麼它是和它不會工作。
  3. 您只預留25個字符的空間,這不是很長(您最長的單詞似乎是14個字符,所以它應該應該沒問題)。
  4. 您應該檢查的fscanf()返回值(事實上,可以用來代替feof())。
+0

我做了14個字符保留。這次,前30個字讀取。 –

+1

@johnalanson Noooo,不要減少它! '25'現在很低,而且你必須有足夠的空間容納字符串終結者! '14'將不起作用。 – unwind

+0

並不幸。 –

0

可以打開的文件和行由行讀這樣的

int main() 
{ 
    /* Used variables */ 
    FILE *file; 
    char *line = NULL; 
    size_t len = 0; 
    ssize_t read; 

    /* Open file descriptor */ 
    file = fopen("simple.txt", "r"); 
    if(file != NULL) 
    { 

     /* Line-by-line read file */ 
     while ((read = getline(&line, &len, file)) != -1) 
     { 
      /* Print line */ 
      printf("%s\n", line); 
     } 

     /* Close file descriptor and free line */ 
     fclose(file); 
     if (line) free(line); 
    } 
    else printf("Can not open file\n"); 

    return 0; 
} 

getline()回報文件上下文-1時,有在文件中沒有更多的行