文章目录
1,刷新流fflush()
- 全缓冲:当流的缓冲区满的时候,自动刷新
行缓冲:当流的缓冲区满的时候/当流的缓冲区中遇到换行符的时候,自动刷新 - 流关闭的时候。当流关闭的时候,系统自动检查,如果缓冲区中还有数据,会把数据写到实际的文件中,去刷新这个流
- 通过函数fflush刷新流
刷新流fflush(),代码分析
a. while(1)死循环,使流一直不能关闭,字符串在缓冲区里,并没有被写入到文件中
#include <stdio.h>
int main(int argc, const char *argv[])
{
FILE *fp;
if((fp = fopen("test.txt","w")) == NULL)//fopen()打开一个普通文件时,默认是全缓冲
{
perror("fopen");
return -1;
}
fputs("abc\n",fp);//此时,往流中写入的字符串只是在流的缓冲区里,只有当缓冲区满,或流关闭的时候,缓冲里的内容才会写到实际的文件中
//fflush(fp);
while(1);
return 0;
}
b. 去掉while(1)死循环,则流会关闭,关闭前自动刷新,缓冲区中的内容会被强制保存进文件
#include <stdio.h>
int main(int argc, const char *argv[])
{
FILE *fp;
if((fp = fopen("test.txt","w")) == NULL)
{
perror("fopen");
return -1;
}
fputs("abc\n",fp);
//fflush(fp);
//while(1);
return 0;
}
c. 使用fflush()强制刷新流,缓冲区中的内容会被写入文件
#include <stdio.h>
int main(int argc, const char *argv[])
{
FILE *fp;
if((fp = fopen("test.txt","w")) == NULL)
{
perror("fopen");
return -1;
}
fputs("abcdef\n",fp);
fflush(fp);
while(1);
return 0;
}
2,定位流ftell(),fseek(),rewind()
#include <stdio.h>
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
- offset参数: 偏移量, 可正可负
- rewind()将流定位到文件开始位置
- 读写流时, 当前读写位置自动后移
示例一 (在文件末尾追加字符‘t’)fseek()
FILE *fp = fopen(“test.txt”, “r+”);
fseek(fp, 0, SEEK_END);
fputc(‘t’, fp);
示例二 (获取文件长度)fseek(),ftell()
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));
3,判断流是否出错和结束
#include <stdio.h>
int ferror(FILE *stream);
int feof(FILE *stream);
- ferror()返回1表示流出错; 否则返回0
- feof()返回1表示文件已到末尾; 否则返回0