5.5 标准I/O(流的刷新和定位)

目录

标准I/O-刷新流

定位流 – ftell/fseek/rewind

标准I/O-判断流是否出错和结束

笔记


标准I/O-刷新流

#include
int fflush(FILE *fp);
 成功时返回 0 ;出错时返回 EOF
 将流缓冲区中的数据写入实际的文件
 Linux 下只能刷新输出缓冲区 , 输入缓冲区丢弃

定位流 – ftell/fseek/rewind

#include
long ftell(FILE *stream);
long fseek(FILE *stream, long offset, int whence);
void rewind(FILE *stream);
 ftell() 成功时返回流的当前读写位置,出错时返回 EOF
 fseek() 定位一个流,成功时返回 0 ,出错时返回 EOF
 whence 参数: SEEK_SET/SEEK_CUR/SEEK_END
 SEEK_SET 从距文件开头 offset 位移量为新的读写位置

 SEEK_CUR :以目前的读写位置往后增加 offset 个位移量
 SEEK_END :将读写位置指向文件尾后再增加 offset 个位移量
 offset 参数:偏移量,可正可负
 打开 a 模式 fseek 无效
 rewind() 将流定位到文件开始位置
 读写流时,当前读写位置自动后移
 示例一 ( 在文件末尾追加字符’ t’)
FILE *fp = fopen(“test.txt”, “r+”);
fseek(fp, 0, SEEK_END);
fputc(‘t’, fp);

//示例二 ( 获取文件长度 )
FILE *fp;
if ((fp = fopen(“test.txt”, “r+”)) == NULL) {
perror(“fopen”);
return -1;
}
fseek(fp, 0, SEEK_END);
printf(“length is %d\n”, ftell(fp));

标准I/O-判断流是否出错和结束

#include
int ferror(FILE *stream);
int feof(FILE *stream);
 ferror() 返回 1 表示流出错;否则返回 0
 feof() 返回 1 表示文件已到末尾;否则返回 0


笔记

流的刷新
int fflush(FILE *fp);
成功时返回 0;出错时返回 EOF
将流缓冲区中的数据写入实际的文件
Linux 下只能刷新输出缓冲区,输入缓冲区丢弃
如果输出到屏幕使用 fflush(stdout)
流的定位:
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 参数:偏移量,可正可负
注意事项:
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++;
}

 

你可能感兴趣的:(开发语言,linux,c++)