文章目录
流的刷新
- 头文件
#include <stdio.h>
- 函数原型
int fflush(FILE *fp);
- 功能:
- 将流缓冲区中的数据刷新出来,写入实际的文件,Linux下只能刷新输出缓冲区,输入缓冲区丢弃
- 返回值:
- 成功时返回0;出错时返回EOF并设置错误码
- 参数:
- 指定要刷新的流
流的定位
- 头文件:
#include <stdio.h>
long ftell(FILE *stream);- 返回当前文件流的文件读写指针的偏移量
void rewind(FILE *stream);- 设置文件读写指针回到文件的开头位置
int fseek(FILE *stream, long offset, int whence);- 用于设置文件流的读写位置。通过添加一个偏移量到指定的起始点来改变文件读写指针的位置(偏移单位字节)
- 返回值:
- 成功返回0,
- 失败返回-1和设置错误码
- 参数:
- offset:偏移量,可正可负可零,分别是向前移动、向后移动或保持不动
- whence:偏移位置,宏来设置( SEEK_SET/SEEK_CUR/SEEK_END )
- SEEK_SET:从距文件开头 offset 位移量为新的读写位置
- SEEK_CUR:以目前的读写位置往后增加 offset个位移量
- SEEK_END:将读写位置指向文件尾后再增加 offset 个位移量
文件的打开使用a模式 fseek无效
rewind(fp) 相当于 fseek(fp,0,SEEK_SET);
以上三个函数只适用2G以下的文件
c
#include <stdio.h>
int main(int argc, const char *argv[])
{
FILE *fp =NULL;
long ret = 0;
char buf[32]={0};
if( (fp=fopen(argv[1], "w+")) == NULL ){
perror("fopen");
return -1;
}
ret = ftell(fp);
printf("ret = %ld\n", ret);
fwrite("helloworld",sizeof(char),10,fp);
ret = ftell(fp);
printf("ret = %ld\n", ret);
//回到文件的开始位置
//fseek(fp, 0, SEEK_SET);
//往前回8个字符
fseek(fp, -8, SEEK_CUR);
ret = ftell(fp);
printf("ret = %ld\n", ret);
fread(buf, sizeof(char), 5, fp);
ret = ftell(fp);
printf("ret = %ld\n", ret);
fclose(fp);
return 0;
}
获取文本大小
c
#include <stdio.h>
int main(int argc, const char *argv[])
{
FILE * fp = NULL;
long file_size = 0;
if(argc < 2){
printf("Usage: %s <source file>\n", argv[0]);
return -1;
}
if((fp = fopen(argv[1], "r")) == NULL ){
printf("fopen source file failed\n");
return -1;
}
// 移动到文件末尾
fseek(fp, 0, SEEK_END);
// 获取当前位置,文件大小
file_size = ftell(fp);
// 输出文件大小
printf("file_size:%ld\n", file_size);
fclose(fp);
return 0;
}
标准IO应用
- 按秒写入时间到文件
latex
每隔1秒向文件test.txt中写入当前系统时间,格式如下:
行号,日期,时间
1,2036-11-15 15:16:43
该程序无限循环,直到按Ctrl-C中断程序
每次执行程序时,系统时间追加到文件末尾,序号递增
1,2036-11-15 15:16:43
2,2036-11-15 11:35:07
3,2036-11-15 11:35:08
c
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define N 32
int main(int argc,const char *argv[])
{
FILE * fp = NULL;
char buf[N]={0};
int linecount = 0;
time_t t;
if (argc < 2){
printf("Usage: %s <filename>\n",argv[0]);
return -1;
}
if ( (fp = fopen(argv[1], "a+")) == NULL )
{
printf("fopen error\n");
return -1;
}
while( fgets(buf,N,fp) != NULL ){
//注意判断是否是一行结束
if( buf[strlen(buf)-1] == '\n' ){
linecount++;
}
}
//printf("test line: %d\n", linecount);
while(1) {
linecount++;
t = time(NULL);
bzero(buf, sizeof(buf));
sprintf(buf, "%d,%s", linecount, ctime(&t));
//printf("test buf: %s\n", buf);
if (fwrite(buf, strlen(buf), 1, fp) < 0) {
perror("fwrite");
break;
}
//强制刷新全缓冲,成功写入文件
fflush(fp);
sleep(1);
}
//没有执行,所以没有刷新全缓冲,文件内容没有写入成功
fclose(fp);
return 0;
}