1.6 fseek和rewind

/*
功能:设置文件偏移位置
 参数1:FILE流
参数2:偏移量
参数3:偏移的位置:SEEK_SET, SEEK_CUR, SEEK_END
返回值:成功返回0,否则返回-1并设置errno
*/
int fseek(FILE *stream, long offset, int whence);
/*
功能:确定文件位置指针位置
参数1:FILE 流
返回值:文件位置指针的当前位置,否则返回-1,并设置errno*/
long ftell(FILE *stream); /*
功能:文件位置指针定义到文件开始位置
参数1:FILE流
返回值:无
*/
void rewind(FILE *stream);

 

下例:用fseek函数以及ftell函数实现确定文件大小的程序:

#include <stdio.h>
#include <stdlib.h>

int main(int argc , char **argv)
{

    FILE *fp;

    if(argc < 2)
    {
        fprintf(stderr,"Usage....\n");
        exit(1);
    }
    fp = fopen(argv[1],"r");
    if(fp == NULL)
    {
        perror("fopen()");
        exit(1);
    }
    fseek(fp,0,SEEK_END);
    printf("%ld\n",ftell(fp));

    exit(0);
}

 

/*
  功能:刷新一个流
参数1:FILE流,如果为NULL,刷新all流
返回值: 成功返回0,否则返回EOF,并设置errno */ int fflush(FILE *stream);

 

 下例:缓冲范例:

#include <stdio.h>
#include <stdlib.h>
/*编译运行结构是“Before while()”也没有打印,
  所以STDOUT是行缓冲,
  解决方法
  1.printf中加\n
  2.在printf后加fflush(stdout);
*/

int main()
{
    int i ;
    printf("Before while()");  // printf("Before while()\n");   
    //fflush(stdout);
    while(1); 
    printf("After while()") 
    exit(0); 
}    

 

缓冲区作用:合并系统调用

行缓冲:换行时候刷新,满了时候刷,强制刷新(stdout)

全缓冲:满了时候刷,强制刷新(默认,除了stdout)

无缓冲:需要立即输出的内容(stderr)

设置缓冲模式:

int setvbuf(FILE *stream, char *buf, int mode, size_t size);

 

posted @ 2015-09-14 22:44  muzihuan  阅读(264)  评论(0编辑  收藏  举报