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 從指定數組獲取