下列三個函數打開一個標準I/O流。
- #include <stdio.h>
- FILE *fopen(const char *restrict pathname, const char *restrict type);
- FILE *fropen(const char *restrict pathname, const char *restrict type, FILE *restrict fp);
- FILE *fdopen(int filedes, const char *type);
返回值:成功返回文件指針,出錯返回NULL
fopen打開一個指定的文件。
freopen在一個指定的流上打開一個指定的文件,如若該流已經打開,則先關閉流。若該流已經定向,則freopen清除該定向。此函數一般用於將一個指定的文件打開爲一個預定義的流:標準輸入、標準輸出或標準出錯。
fdopen獲取一個現有的文件描述符,並使一個標準的I/O流與該描述符相結合。此函數常用於由創建管道和網絡通信通道函數返回的描述符。因爲這些特殊類型的文件不能用標準I/O fopen函數打開,所以必須先調用設備專用函數以獲得一個文件描述符,然後用fdopen使一個標準I/O流與該描述符相關聯。
fopen和freopen是ISO C的所屬部分。而ISO C並不涉及文件描述符,所以僅有POSIX.1具有fdopen。
type參數質的個對該I/O流的讀、寫方式,ISO C規定type參數可以有15種不同的值,它們示於表5.2中。
type |
Description |
---|---|
r or rb |
open for reading |
w or wb |
truncate to 0 length or create for writing |
a or ab |
append; open for writing at end of file, or create for writing |
r+ or r+b or rb+ |
open for reading and writing |
w+ or w+b or wb+ |
truncate to 0 length or create for reading and writing |
a+ or a+b or ab+ |
open or create for reading and writing at end of file |
表5.2 打開標準I/O流的type參數
對於fdopen,type參數的意義稍有區別。因爲該描述符已被打開,所以fdopen爲寫而打開並不截短該文件。
當以讀和寫類型打開一個文件時(type+符號),具有下列限制:
- 如果中間沒有fflush、fseek、fsetpos或rewind,則在輸出的後面不能直接跟隨輸入。
- 如果中間沒有fseek、fsetpos或rewind,或者一個輸入操作沒有到達文件尾端,則在輸入操作之後不能直接跟隨輸出。
Restriction |
r |
w |
a |
r+ |
w+ |
a+ |
---|---|---|---|---|---|---|
file must already exist |
• |
• |
||||
previous contents of file discarded |
• |
• |
||||
stream can be read |
• |
• |
• |
• |
||
stream can be written |
• |
• |
• |
• |
• |
|
stream can be written only at end |
• |
• |
表5.3 打開一個標準I/O流的6種不同的方式
注意,在指定w或a類型創建一個新文件時,我們無法說明該文件的訪問權限位。除非引用終端設備,否則按系統默認的情況,流被打開時是全緩衝的。若流引用終端設備,則該流是行緩衝的。一旦打開了流,那麼在對該流執行任何操作之前,如果希望,則可使用上一節所述的setbuf和setvbuf改變緩衝的類型。
調用fclose關閉一個打開的流。
- #include <stdio.h>
- int fclose(FILE *fp);
返回值:成功返回0,出錯返回EOF
在該文件被關閉之前,沖洗緩衝區中的輸出數據。丟棄緩衝區中的任何輸入數據。
當一個進程正常終止時(直接調用exit函數,或從main函數返回),則所有帶未寫緩衝數據的標準I/O流都會被沖洗,所有打開的標準I/O溜溜都會被關閉。