刷新流
int fflush(FILE *fp);
成功时 返回0;出错时返回EOF
将流缓冲区中的数据写入实际的文件
Linux下只能刷新输出缓冲区,输入缓冲区丢弃
定位流-ftell/fseek/rewind
#include<stdio.h>
long ftell(FILE *fp);
long fseek(FILE *fp,long offset,int whence);
void rewind(FILE *fp);
ftell()成功时返回流的当前读写位置,出错返回EOF
fseek()定位一个流,成功时返回0,出错返回EOF
offset为偏移量,可正负
whence参数:SEEK_SET/SEEK_CUR/SEEK_END
rewind(fp) = fseek(fp,0,SEEK_SET)
注意事项:
打开a模式,fseek无效
这三个函数只适用于2G以下的文件
格式化输出/输入
int fprintf(FILE *stream,const char *f...);
int sprintf(char *s,cahr *fmt,...);
int fscanf(FILE *stream,const cahr *format,...);
int sscanf(const char *str,const cahr *format,...);
思考与练习
![](https://img-blog.csdnimg.cn/img_convert/4dd0e2cbbf29001fb4014d6903ecc60b.png)
利用time()函数来获取系统时间(秒数)
time_t time(time_t *seconds);
利用localtime()将系统时间转换为本地时间
struct tm *localtime(const time_t *timer);
程序如下
#include <time.h>
#incldue <stdio.h>
#include <unistd.h>
#include <string.h
int main(int argc ,char *argv[]){
FILE *fp;
char buf[32];
int count = 0;
time_t ctime;
struct tm *timestr;
fp = fopen("test.txt","a+");
//计算行号
while(!fgets(buf,32,fp)){
if(buf[strlen(buf)-1]=='\n'){
count++;
}
}
while(1){
ctime = time(NULL);
printf("time = %ld",ctime);
timestr = localtime(&ctime);
printf("%d:%d:%d-%d:%d:%d\n",timestr->tm_year+1960,timestr->tm_mon+1,time->tm_mday,
timestr->tm_hour,timestr->tm_min,timestr->tm_sec);
fprintf("%d,%d:%d:%d-%d:%d:%d\n",count,timestr->tm_year+1960,timestr->tm_mon+1,time->tm_mday,
timestr->tm_hour,timestr->tm_min,timestr->tm_sec);
fflush(fp);
count++;
sleep(1);
}
fclose(fp);
return 0;
}