文件IO fflush fseek ftell rewind feof ferror

fprintf()  、 sprintf、 snprintf :

int fprintf(FILE *stream, const char *format, ...);
int sprintf(char *str, const char *format, ...); 
int snprintf(char *str, size_t size, const char *format, ...);
  1. #include <stdio.h>
  2. int main()
  3. {
  4. FILE * fp = fopen("a.txt","w+");
  5. if(fp == NULL)
  6. return -1;
  7. fprintf(fp , "I am a stutent %d\n",100);
  8. fclose(fp);
  9. return 0;
  10. }




fscanf()  、 sscanf() :

int fscanf(FILE *stream, const char *format, ...);
int sscanf(const char *str, const char *format, ...);



fflush(): 清空刷新缓冲区的内容
  1. #include <stdio.h>
  2. int main()
  3. {
  4. printf("hello");
  5. fflush(stdout); //刷新了hello才能输出来,也可以fflush(NULL)
  6. while(1)
  7. {
  8. }
  9. printf("h");
  10. return 0;
  11. }


如果没有fflush,死循环前的hello也不会输出
  1. #include <stdio.h>
  2. int main()
  3. {
  4. printf("hello");
  5. while(1)
  6. {
  7. }
  8. printf("h");
  9. return 0;
  10. }


fflush(NULL) //清空所有IO缓冲区

缓冲区默认8192字节 【8K】,满了也刷新




fseek    ftell  rewind   对读写指针位置的操作

int fseek(FILE *stream, long offset, int whence); 移动读写指针

offset 正数 向后偏移  负数 向前偏移
whence 三个基准坐标
seek_set     文件起始位置
seek_cur     文件当前位置
seek_end    文件末尾位置

fseek实现rewind: 把读写指针移动到开头  -----> fseek( fp , 0 , SEEK_SET);
fseek( fp , 0 , SEEK_END);把读写指针移动到末尾


如果读写指针在最后了,再向后偏移 属于扩展一个文件
如果读写指针在最前了,再向前偏移,出错,没有意义

fseek扩展的话,后面需要跟个写操作,否则无效



long ftell(FILE *stream); 
返回当前读写位置

void rewind(FILE *stream); 
读写位置    重置到       开头



在C语言中,常用的文件检测函数有以下几个:


1. 文件结束检测函数feof函数

调用格式:

1
feof(文件指针);

功能:判断文件是否处于文件结束位置,如文件结束,则返回值为1,否则为0。

2. 读写文件出错检测函数

ferror函数调用格式:

1
ferror(文件指针);

功能:检查文件在用各种输入输出函数进行读写时是否出错。如ferror返回值为0表示未出错,否则表示有错。


3. 文件出错标志和文件结束标志置0函数

clearerr函数调用格式:

1
clearerr(文件指针);

功能:本函数用于清除出错标志和文件结束标志,使它们为0值。





posted @ 2014-09-02 21:45  我爱背单词  阅读(368)  评论(0编辑  收藏  举报