lv4 嵌入式开发-5 流刷新定位

目录

1 标准I/O – 刷新流

2 定位流 – ftell/fseek/rewind

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

4 练习


前言:掌握流的刷新,流的定位,检测流结束和出错。文件写完后,文件指针指向文件末尾,流刷新定位解决这个问题。

1 标准I/O – 刷新流

#include 
	
int fflush(FILE *fp);

成功时返回0;出错时返回EOF

将流缓冲区中的数据写入实际的文件

Linux下只能刷新输出缓冲区,输入缓冲区丢弃

示例:

#include 
#include 

int main() {
	
	printf("abcdef");
	//fflush(stdout);  //不刷新流,屏幕无输出。
	while(1)
	{
		sleep(1);
	}
	return 0;
}


示例2

#include 
#include 
int main(int argc,char *argv[]){

//   printf("abcdefg");
//   fflush(stdout);
   FILE *fp;
   fp=fopen("1.txt","w");
   if(fp==NULL){
      perror("fopen");
      return 0;
   } 

   fwrite("abcdef",7,1,fp);  
   fflush(fp);                //刷新才能写入到文件

   while(1){

      sleep(1);
   }


}

 

2 定位流 – ftell/fseek/rewind

#include  
long ftell(FILE *stream);
long fseek(FILE *stream, long offset,  int whence);
void rewind(FILE *stream);

ftell() 成功时返回流的当前读写位置,出错时返回EOF,不超过long范围

fseek()定位一个流,成功时返回0,出错时返回EOF

whence参数:SEEK_SET/SEEK_CUR/SEEK_END

SEEK_SET 从距文件开头 offset 位移量为新的读写位置

SEEK_CUR:以目前的读写位置往后增加 offset 个位移量

SEEK_END:将读写位置指向文件尾后再增加 offset 个位移量

offset参数:偏移量,可正可负

打开a模式 fseek无效

rewind()将流定位到文件开始位置

注意事项:

-文件的打开使用a模式 fseek无效

-rewind(fp) 相当于 fseek(fp,0,SEEK_SET);

-这三个函数只适用2G以下的文件

-读写流时,当前读写位置自动后移

示例一(在文件末尾追加字符’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));

示例

#include 

int main(int argc,char *argv[]){
    
   FILE *fp;
   fp=fopen("1.txt","w");   //a模式下不能再次定位
   if(fp==NULL){
      perror("fopen");
      return 0;
   }

   fwrite("abcdef",6,1,fp);
   printf("current fp=%d\n",(int)ftell(fp));

//   fseek(fp,-2,SEEK_CUR);   //结果agcdvv
//   fseek(fp,3,SEEK_SET);    //结果abcvvv

   rewind(fp);
   printf("After rewind fp=%d\n",(int)ftell(fp));
   fwrite("vvv",3,1,fp);     //结果vvvdef


}

 

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

#include  
int ferror(FILE *stream);
int feof(FILE *stream);

ferror()返回1表示流出错;否则返回0

feof()返回1表示文件已到末尾;否则返回0

4 练习

流的刷新及定位用到了哪些函数?分别有什么作用?

  • fflush(FILE * stream) 用于立刻将流直接写入文件磁盘
  • long ftell(FILE *stream) 用于返回当前读写指针的位置,出错时返回EOF
  • long fseek(FILE *stream, long offset, int wence); 用于定位流的指针位置,可以从头偏移,当前位置偏移,尾部偏移
  • void rewind(FILE *strea) 用于刷新定位到文件开始位置

你可能感兴趣的:(嵌入式开发,linux,I/O)