fopen, fdopen, freopen - stream open functions
#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);
fopen
打开指定的文件
freopen
在指定的流上打开特定的文件,并且该stream如果先前打开了就先关闭它:经常用于打开指定的文件作为标准输入输出或者错误流
fdopen
通过fd
打开流: 用于处理pipe
和network communication channel
返回的fd
,因为这些特殊的文件不能用常规方式打开
参数mode
的选项如图:
因为Unix
中不区别文本文件还是二进制文件,所以“b”
是没有影响的
- fdopen的参数mode有些不同
因为fd
代指的文件已经打开了,所以为write
操作打开文件不会truncate(截短)
文件。
以append
打开的文件,每次write
操作都在文件尾部。
- 多个进程使用标准IO使用
append
打开同一个文件,来自每个进程的数据会被正确地写入文件里
当文件被打开用于reading and writing
,会有如下的限制:
1. Output不能再没有fflush,fseek,fsetpos or rewind
下,直接就继续Input
2. Input不能在没有fseek,fsetpos,rewind
或者Input操作遇到文件结尾的情况下,直接跟着Output
default bufferring
所有打开的stream
默认为fully buffered
,除非其是用于terminal device
的(line buffered)。
fclose - close a stream
#include<stdio.h>
int fclose(FILE *fp);
//Returns: 0 if OK, EOF on error
在fclose
之前任何buffered output
data都会被flush
,任何input data
会被丢弃(discard).
当进程通过调用exit
或者从main
正常返回的进程,会刷新所有缓存的数据,并且关闭所有打开的IO stream
.