Linux 流处理函数
流操作函数的对象不是文件描述符而是流缓冲区
//流的打开与关闭
//打开
#include <stdio.h>
FILE *fopen(const char *path, const char *mode);//打开指定的文件
FILE *fdopen(int fd, const char *mode);
//打开文件描述符指定的流
FILE *freopen(const char *path, const char *mode, FILE *stream);
//在指定 的流上打开一个指定的文件,一般用于将一个指定的文件打开为一个预定义的流
return a FILE pointer. Otherwise, NULL is returned
//关闭
#include <stdio.h>
int fclose(FILE *fp);
0 is returned. Otherwise, EOF is returned
//流的缓存方式
全缓存:缓冲区满操作
行缓存:遇到换行符 调用进行操作
无缓存:不缓存
//特征
1.仅当输入和输出不涉及交互设备时,才是全缓存的,大部分是行缓冲
2.标准出错不是全缓冲
//流的缓存区修改
#include <stdio.h>
void setbuf(FILE *stream, char *buf);
void setbuffer(FILE *stream, char *buf, size_t size);
void setlinebuf(FILE *stream);
int setvbuf(FILE *stream, char *buf, int mode, size_t size);
0 on success. It returns non-zero on failure
model类型
_IONBF unbuffered
_IOLBF line buffered
_IOFBF fully buffered
//流的读写
字符读写
行读写
块读写
#include <stdio.h>
int fgetc(FILE *stream);
int getc(FILE *stream);//可被实现为宏,效率较高
int getchar(void);//只能从标准输入流中输入数据
char *fgets(char *s, int size, FILE *stream);//从strean中读出一行数据送到s指定的缓存区中,size指定缓冲区的大小
char *gets(char *s);
int ungetc(int c, FILE *stream);
//按字节写函数
#include <stdio.h>
int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c);
int puts(const char *s);
int fputs(const char *s, FILE *stream);
return the character written as an unsigned char cast to an int or EOF on error.
//@@linux中可以使用 CTRL+D 来输入EOF符号
//二进制读写
#include <stdio.h>
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);
return the number of items successfully read or written (i.e., not the number of characters). If an error occurs, or the end-of-file is reached,
the return value is a short item count (or zero)
//流的出错处理
#include <stdio.h>
void clearerr(FILE *stream);//清除出错标志
int feof(FILE *stream);//判断是否到文件结尾
int ferror(FILE *stream);//判断是否出错
int fileno(FILE *stream);
//流的冲洗
操作完成后内核的缓冲区可以将数据清空也可以保存到流对应的文件中
fflush
_fpurge
//流的定位
#include <stdio.h>
int fseek(FILE *stream, long offset, int whence);//改变文件的偏移量 whence指明参数的偏移起点 offset 是流的偏移值
long ftell(FILE *stream);//返回流当前文件位置
void rewind(FILE *stream);//将偏移量设定为流的起始部分
int fgetpos(FILE *stream, fpos_t *pos);//得到读写指针的位置
int fsetpos(FILE *stream, fpos_t *pos);//定位读写至真的位置
//二制文件的偏移量使用长整形确定
#include <stdio.h>
int fseeko(FILE *stream, off_t offset, int whence);
off_t ftello(FILE *stream);
//临时文件
#include <stdio.h>
char *tmpnam(char *s);//产生一个与系统中已经存在的文件名不相同的临时文件名
//每次调用会产生一个新的带路径的完整新文件名
在一个应用中多次调用tmpam 应使s非空
char *tempnam(const char *dir, const char *pfx);
可以指定临时文件存放的目录和文件名的前缀 dir给出目录 pfx给出文件名前缀