标准I/0——流的基本操作

流的打开

FILE *fopen(const char *path,const har *mode)
// 成功则返回流指针,出错则返回NULL
  1. mode参数:
r/rb 只读,文件必须存在
r+/r+b 可读写,文件必须存在
w/wb 只写,文件不存在则创建
w+/w+b 可读写
a/ab 文件存在则追加,否则创建新文件
a+/a+b 追加可读写

流的关闭

int fclose(FILE *stream);
// 成功返回0,失败返回EOF并设置errno

流的刷新

int fflush(FILE *stream);
// 将输出缓冲区的数据写入实际文件

流的定位

long ftell(FILE *stream);
// 返回当前文件的读写位置
long fseek*FILE *stream,long offset,int whence);
// 刷新流的位置
// whence参数:SEEK_SET/SEEK_CUR/SEEK_END
void rewind(FILE *stream);
// 将pos定位到文件开始
int feof(FILE *stream);
// 流到了文件末尾则返回1,否则返回0
int ferror(FILE *stream);
// 文件出错则返回1 , 否则返回0

文件读写

按字符读写

// 读字符
int fgetc(FILE *stream);
int getc(FILE *stream);
// 二者完全等价
int getchar(void);
int fgetc(stdin);
//  二者完全等价
// 写字符
int fputc(int c,FILE *stream);

按行读写

// 按行读
char *gets(char *s);// 容易造成缓冲区溢出
char *fgets(char *s,int size , FILE *stream);//遇到'\n',或者size-1个字符停止
// 按行写
int puts(const char *s);//会多输出一个换行符
int fputs(const char *s ,  FILE *stream);// 返回输出字符数

按指定对象读写

// 读
size_t fread(void *ptr,size_t size , size_t n , FILE  *stream);
// 写
size_t fwrite(const void *ptr,size_t size ,size n , FILE *stream);

格式化输出

int sprintf(char *s,const char *format , ...);
int fprintf(FILE *stream,const char *format,...);
int printf(const char *format,...);

猜你喜欢

转载自blog.csdn.net/qq_45279570/article/details/112918491