jiaan
#include<stdio.h>
#include<unistd.h>
#include<time.h>
int main(int argc,char *argv[])
{
       FILE  *fp;
       time_t t;
       if(argc < 2)
       {
             printf("Usage: %s<file>\n",argv[0]);
             return -1;
        }  
        if((fp = fopen(argv[1],"w")) == NULL)
         {
            perror("fail to fopen");
            return -1;  
         }
        while(1){
               time(&t);
               fprintf(fp,"%s",ctime(&t));
               sleep(1);
        }  
       fclose(fp);
       fp = NULL;  
       return 0;
}

  作者在  gcc time_3.c -o time_3 

           ./time_3  1.txt 

之后,并没有在1.txt中查看到数据。经过一番搜查后知道了,数据先是存在缓存中,有缓存刷新时,才能从缓存中读出数据写到文件中,然而fprintf()自己读完一行数据后并不能自己刷缓存,需要在sleep(1)上一行加  fflush(fp);就可以刷新缓存,程序就可以编译运行成功了。经查,1.txt中出现了期待已久的数据。

相关文章:

  • 2021-10-09
  • 2021-10-29
  • 2021-08-21
  • 2021-08-05
  • 2022-01-08
  • 2022-12-23
  • 2021-07-08
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-07
  • 2021-05-31
  • 2022-03-01
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案