Linux檔案IO和標準IO
阿新 • • 發佈:2018-12-21
Linux 檔案IO
Linux中做檔案IO最常用到的5個函式是: open , close , read , write 和 lseek ,不是ISO C的組成部分,這5個函式是不帶緩衝的IO,也即每個read和write都呼叫了核心的一個系統呼叫。
#include <fcntl.h> #include <unistd.h> int open(const char *pathname, int oflag, ... /* mode_t mode */);/* 成功返回檔案描述符, 失敗返回-1 */ int close(int filedes);/* 成功返回0, 失敗返回-1 */ off_t lseek(int filedes, off_t offset, int whence);/* 成功返回新的檔案偏移量,出錯返回-1 */ ssize_t read(int filedes, void *buf, size_t nbytes);/* 成功則返回讀取到的位元組數,若已到檔案的結尾返回0,出錯返回-1 */ ssize_t write(int filedes, void *buf, size_t nbytes);/* 成功則返回寫入的位元組數,出錯返回-1 */
Linux 標準IO
標準IO庫提供緩衝功能,減少系統呼叫。
- 全緩衝。即填滿IO緩衝區後才進行IO操作。
- 行緩衝。遇到換行符時執行IO操作。 * 無緩衝。
一般情況下,標準出錯無緩衝。如果涉及終端裝置,一般是行緩衝,否則是全緩衝。 可用 setbuf 和 setvbuf 函式設定緩衝型別已經緩衝區大小,使用fflush函式沖洗緩衝區。
開啟流
使用 fopen , freopen , fdopen 三個函式開啟一個流,這三個函式都返回FILE型別的指標。
#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 *dopen(int filedes, const char *type); /* 成功返回FILE型別指標,出錯返回NULL */
- fopen 開啟一個指定的檔案。
- freopen 在一個指定的流上開啟一個檔案,比如在標準輸出流上開啟某檔案。
- dopen 開啟指定的檔案描述符代表的檔案。常用於讀取管道或者其他特殊型別的檔案,因為這些檔案不能直接用fopen開啟。
- type 引數指定操作型別,入讀寫,追加等等。
關閉流
fclose 函式關閉一個流:
#include <stdio.h>
int flose(FILE *fp);
/* 成功返回0,出錯返回EOF */
讀寫流
- 每次一個字元的IO流
#include <stdio.h> /* 輸入 */ int getc(FILE *fp); int fgetc(FILE *fp); int getchar(void); /* 上面三個函式的返回值為int,因為EOF常實現為-1,返回int就能與之比較 */ /* 判斷出錯或者結束 */ int ferror(FILE *fp); int feof(FILE *fp); void clearerr(FILE *fp); /* 清除error或者eof標誌 */ /* 把字元壓送回流 */ int ungetc(intc FILE *fp); /* 輸出 */ int putc(int c, FILE *fp); int fputc(int c, FILE *fp); int putchar(int c);
- 每次一行的IO流
#include <stdio.h>
/* 輸入 */
char *fgets(char *restrict buf, int n, FILE *restrict fp);
char *gets(char *buf);
/* gets由於沒有指定緩衝區,所以有可能造成緩衝區溢位,要小心 */
/* 輸出 */
int fputs(char *restrict buf, FILE *restrict fp);
int puts(const char *buf);
- 二進位制讀取讀寫檔案流,常作為讀取開啟的整個流檔案
#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);
/* 返回值:讀或寫的物件數 */
定位流
#include <stdio.h>
long ftell(FILE *fp);
/* 成功則返回當前檔案位置指示,出錯返回-1L */
int fseek(FILE *fp, long offset, int whence);
/* 成功返回0, 出錯返回非0 */
int fgetpos(FILE *restrict fp, fpos_t *restrict pos);
int fsetpos(FILE *fp, fpos_t *pos);
/* 成功返回0,出錯返回非0 */
格式化輸出IO流
執行格式化輸出的主要是4個 printf 函式:
- printf 輸出到標準輸出
- fprintf 輸出到指定流
- sprintf 輸出到指定陣列
- snprintf 輸出到指定陣列並在陣列的尾端自動新增一個null位元組
格式化輸入IO流
格式化輸入主要是三個 scanf 函式:
- scanf 從標準輸入獲取
- fscanf 從指定流獲取
- sscanf 從指定陣列獲取