2015-04-21 84 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时,有在文件中没有更多的行