- 论坛徽章:
- 0
|
Standard I/O Library
Buffering:标准I/O提供缓冲区的目的是使得调用读写次数最少。而且,其尝试自动为每个I/O流完成缓冲,减免了程序的考虑。不幸的是,正是这个缓冲机制产生了最多的疑惑。
三种缓冲机制:1、fully buffered 实际的I/O当标准I/O被填满是发生。缓冲区通常通过调用malloc函数获得
2、line buffered 当遇到换行符时,执行I/O操作。
3、unbuffered标准I/O不缓冲字符。
#include <stdio.h>
Void setbuf(FILE *restrict fp, char *restrict buf); int setvbuf(FILE *restrict fp, char *restrict buf, int mode, size_t size);
如果要改变缺省的缓冲机制,可以调用上面两个函数去修改。Setbuf可以打开与关闭缓冲。
Setvbuf可以指定缓冲类型,参数mode可为:
_IOEBF fully buffered
_IOLBF line buffered
_IONBF unbuffed
任何时候,我们可以强制流被flush通过函数
Int fflush(FILE *fp);
打开流:#include <stdio.h> FILE *fopen(const char *restrict pathname, const char *restrict type);
FILE *freopen(const char *restrict pathname, const char *restrict type, FILE *restrict fp);
FILE *fdopen(int fields, const char *type);
fopen打开一个指定文件
freopen用指定的流打开指定的文件
fdopen用指定的流关联已打开的文件标识符
参数type可为:
r or rb 读
w or wb 清空写
a or ab 添加写
r+ or r+b or rb+ 读写
w+ or w+b or wb+ 清空文件读写
a+ or a+b or ab+ 追加读写
用字母b区分字符文件与可执行文件。因为unix内核不区分这两种文件,所以字母b没有作用。
关闭流使用函数int fclose(FILE *fp);
读与写文件流,三种类型:
1 一次写一个字符
2 一次写一行
3 直接I/O
#include <stdio.h>
int getc(FILE *fp); int fgetc(FILE *fp); int getchar(void); 成功返回下一个字符,文件尾或错误返回EOF。
int ferror(FILE *fp); int feof(FILE *fp);区分返回EOF时是遇到错误还是达到文件结尾。
int ungetc(int c, FILE *fp);将读入的字符再推回文件流。
输出函数:int putc(int c, FILE *fp); int fputc(int c, FILE *fp); int putchar(int c);
Line at a time I/O:
char *fgets(char *restrict buf, int n, FILE *restrict fp);
char *gets(char *buf);
int fputs(const char *restrict str, FILE *restrict fp);
int puts(const char *str);
Binary I/O:#include <stdio.h>
size_t fread(void *restrict ptr, size_t size, size_t nobj, FILE *restrict fp);
size_t fwrite(const void *restrict ptr, size_t size, size_t nobj, FILE *restrict fp);
Position a stream:#include <stdio.h>
long ftell(FILE *fp);
int fseek(FILE *fp, long offset, int whence);
void rewind(FILE *fp);
参数whence可为:SEEK_SET,SEEK_CUR,SEEK_END
off_t ftello(FILE *fp); int fseeko(FILE *fp, off_t offset, int whence);
格式化 I/O:
#include <stdio.h>
int printf(const char *restrict format,…);
int fprintf(FILE *restrict fp, const char *restrict format,…);
int scanf(const char *restrict format, …);
int fscanf(FILE *restrict fp, const char *restrict format, …);
临时文件:ISO C定义了两个函数创建临时文件。
Char *tmpnam(char *ptr);
FILE *tmpfile(void);
tmpname函数生成一个路径名 。 |
|