流的刷新
int fflush(FILE *fp);
成功时返回0;出错时返回EOF
将流缓冲区中的数据写入实际的文件
Linux下只能刷新输出缓冲区,输入缓冲区丢弃
如果输出到屏幕使用fflush(stdout)
加了fflush()函数才能打印出来。
流的定位
long ftell(FILE *stream);//函数获取一个文件指针的当前位置
long fseek(FILE *stream, long offset, int whence);
void rewind(FILE *stream);
fseek 参数whence参数:SEEK_SET/SEEK_CUR/SEEK_END
SEEK_SET 从距文件开头 offset 位移量为新的读写位置
SEEK_CUR:以目前的读写位置往后增加 offset 个位移量
SEEK_END:将读写位置指向文件尾后再增加 offset 个位移量
offset参数:偏移量,可正可负
fwrite(const void*buffer,size_t size,size_t count,FILE*stream);
(1)buffer:是一个指针,对fwrite来说,是要输出数据的地址。
(2)size:要写入的字节数;
(3)count:要进行写入size字节的数据项的个数;
(4)stream:目标文件指针。
注意事项:
1.文件的打开使用a模式 fseek无效
2.rewind(fp) 相当于 fseek(fp,0,SEEK_SET);
3.这三个函数只适用2G以下的文件
编译告警错误:
ffseek_t.c:13:11: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long int’ [-Wformat=]
printf(“current fp=%d\n”,ftell(fp));
表示参数类型不匹配
格式化输出
int fprintf(FILE *stream, const char *fmt, …);
int sprintf(char *s, const char *fmt, …);
成功时返回输出的字符个数;出错时返回EOF
格式化输入
int fscanf(FILE *stream, const char *format, …);
int sscanf(const char *str, const char *format, …);
重点掌握sprintf 和sscanf
编译告警:
wsystime.c:16:13: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘time_t {aka long int}’ [-Wformat=]
printf(“ctime=%d\n”,ctime);
表示类型不匹配 期望的是int但是参数传的是time_t
解决办法:在参数前加强制类型转换
标准IO练习
time()用来获取系统时间(秒数)
time_t time(time_t *seconds) 1970.1.1 0:0:0
localtime()将系统时间转换成本地时间
struct tm *localtime(const time_t timer)
struct tm {
int tm_sec; / 秒,范围从 0 到 59 /
int tm_min; / 分,范围从 0 到 59 /
int tm_hour; / 小时,范围从 0 到 23 /
int tm_mday; / 一月中的第几天,范围从 1 到 31 /
int tm_mon; / 月份,范围从 0 到 11 /
int tm_year; / 自 1900 起的年数 /
int tm_wday; / 一周中的第几天,范围从 0 到 6 /
int tm_yday; / 一年中的第几天,范围从 0 到 365 /
int tm_isdst; / 夏令时 */
};
注意:
int tm_mon; 获取的值要加1是正确的月份
int tm_year; 获取的值加1900是正确的年份
获取文件内的所有行数量:
while(fgets(buf,32,fp)!=NULL){
if(buf[strlen(buf)-1] =='\n'){ //注意判断是否是一行结束
linecount++;
}
}
写完文件记得fflush ,写到磁盘里面去。
标准IO磁盘文件的缓冲区一般为4096
注意和标准输出的全缓冲区别,标准输出是1024
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int argc,char *argv[]){
FILE *fp;
time_t ctime;
struct tm *ctimestr;
int linecount = 0;
char buf[32];
fp=fopen("test.txt","a+");
if(fp==NULL){
perror("fopen");
return 0;
}
//calculate test.txt line
while(fgets(buf,32,fp)!=NULL){
if(buf[strlen(buf)-1] =='\n'){//判断是不是读完一行了,行尾是\n(buf减1是最后一位)
linecount++;
}
}
while(1){
ctime = time(NULL);
//printf("ctime=%d\n",(int)ctime);
ctimestr = localtime(&ctime);
printf("%04d-%02d-%02d %02d:%02d:%02d\n",ctimestr->tm_year+1900,ctimestr->tm_mon+1,ctimestr->tm_mday,
ctimestr->tm_hour,ctimestr->tm_min,ctimestr->tm_sec);
fprintf(fp,"%d, %04d-%02d-%02d %02d:%02d:%02d\n",linecount,ctimestr->tm_year+1900,ctimestr->tm_mon+1,ctimestr->tm_mday,
ctimestr->tm_hour,ctimestr->tm_min,ctimestr->tm_sec);
fflush(fp);
linecount++;
sleep(1);
}
fclose(fp);
}