为什么我的代码只使用fscanf存储文件中的最后一个单词?

时间:2012-12-19 18:16:06

标签: c scanf

这里的printf语句只打印出文件里面的最后一个单词。那是为什么?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
    FILE *fp;
    int c;
    char string[100];
    fp = fopen("exam.txt", "r");
    c = getc(fp);
    while(c!=EOF)
    { 
        fscanf(fp, "%s", string);
        c = getc(fp);
    }
    fclose(fp);
    printf("%s", string);
    return 0; 

}

1 个答案:

答案 0 :(得分:3)

因为你最后只打印一次......

printf("%s", string); 

你需要在这个循环中打印:

while(c!=EOF)
{ 
    fscanf(fp, "%99s", string);
    printf("%s\n", string);  // now you can see the files as you read it.
     c = getc(fp);
} 

如果你想看到每一行。你每次都要覆盖string

此外,在使用之前,您不会初始化int c

细分fscanf()

 fscanf(fp,       // read from here   (file pointer to your file)
        "%99s",   // read this format (string up to 99 characters)
         string); // store the data here (your char array)

您的循环条件是下一个字符不是EOF,意味着文件结束(在从文件读出所有数据后发生的条件)

所以:

while (we're not at the end of the file)
     read up a line and store it in string
     get the next character

你会注意到你的算法没有检查该字符串中的任何内容,它只是写入它。这将每次覆盖那里的数据。这就是为什么你只看到你文件的最后一行,因为你继续写string并且那里的最后一件事恰好是你在看到EOF字符并突破while循环之前读到的最后一行。 / p>