发布时间:2025-12-10 19:35:56 浏览次数:9
Linux学习——流刷新定位、格式化输入和输出Linux学习笔记_fseek(fp,0,seek_set);
目录
一、流的刷新
二、流的定位:
fseek 参数whence参数:SEEK_SET/SEEK_CUR/SEEK_END
注意事项:
三、格式化输出
四、格式化输入
五、 标准IO练习题
程序:
结果:
注意:
int fflush(FILE *fp);
成功时返回0;出错时返回EOF
将流缓冲区中的数据写入实际的文件
Linux下只能刷新输出缓冲区,输入缓冲区丢弃
如果输出到屏幕使用fflush(stdout)
实验程序:
#include <stdio.h>#include <unistd.h>int main(){//printf("abcdef");//fflush(stdout);FILE * fp;fp = fopen("1.txt","w");fwrite("abcdefg",7,1,fp);fflush(fp);while(1){sleep(1);}}希望我今天分享的这篇文章可以帮到您。
实验结果:
long ftell(FILE *stream);
long fseek(FILE *stream, long offset, int whence);
void rewind(FILE *stream);
SEEK_SET 从距文件开头 offset 位移量为新的读写位置
SEEK_CUR:以目前的读写位置往后增加 offset 个位移量
SEEK_END:将读写位置指向文件尾后再增加 offset 个位移量
offset参数:偏移量,可正可负
1.文件的打开使用a模式 fseek无效
2.rewind(fp) 相当于 fseek(fp,0,SEEK_SET);
3.这三个函数只适用2G以下的文件
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, …);
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; /* 夏令时 */
};
#include <stdio.h>#include <time.h>#include <unistd.h>#include <string.h>int main(){int i = 0;time_t times;FILE * fp;char buf[32];struct tm* ge;fp = fopen("2.txt","a+");if(fp == NULL){perror("fopen");return 0;}while(fgets(buf,32,fp) != NULL){if(buf[strlen(buf)-1] == '\n'){i++;}}while(1){times = time(NULL);//printf("%d\n",(int)times);ge = localtime(×);printf("%2d:%4d-%2d-%2d %2d:%2d:%2d\n",i,ge->tm_year+1900,ge->tm_mon+1,ge->tm_mday,ge->tm_hour,ge->tm_min,ge->tm_sec);fprintf(fp,"%2d:%4d-%2d-%2d %2d:%2d:%2d\n",i,ge->tm_year+1900,ge->tm_mon+1,ge->tm_mday,ge->tm_hour,ge->tm_min,ge->tm_sec);i++;fflush(fp);sleep(1);}fclose(fp);}标准IO磁盘文件的缓冲区一般为4096
注意和标准输出的全缓冲区别,标准输出是1024