【问题标题】:Why does the first run of this simple file-read program takes 30 secs to execute?为什么这个简单的文件读取程序的第一次运行需要 30 秒才能执行?
【发布时间】:2013-06-19 02:47:23
【问题描述】:

当我第一次运行程序时,文件被创建。但似乎 while 循环需要很长时间才能结束。由于文件现在是空的,它不会在文件的开头得到一个EOF吗?

#include<stdio.h>
void main(){
    FILE *p;
    int b, a=0;b=0;
    p=fopen("text.txt", "a+");
    while((b=fscanf(p,"%d",&a)) != EOF)
        printf("%d\n",a);
    fseek(p, 0, SEEK_END);
    fprintf(p, " %d %d",1,6);
    fflush(p);
    fclose(p);
}

【问题讨论】:

  • 为什么 `int b, a=0;b=0;` 而不是 int a=0,b=0;?
  • 追加模式下不需要 fseek
  • 您可以尝试分析程序以查看其大部分时间都花在了哪里。

标签: c file-io eof stdio


【解决方案1】:

确保fscanf returns 1:

#include<stdio.h>
int main(){
    FILE *p;
    int b=0, a=0;
    p=fopen("text.txt", "a+");
    while((b=fscanf(p,"%d",&a)) == 1)
        printf("%d\n",a);
    // no need to seek, or flush
    fprintf(p, " %d %d",1,6);
    fclose(p);
    return 0;
}

【讨论】:

  • @user2499377,如果您有非数字数据,您可以使用 fscanf 永远循环,因为它永远不会跳过该数据。
猜你喜欢
  • 1970-01-01
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-22
  • 1970-01-01
相关资源
最近更新 更多