linux程式設計主題之標準I O與高階I O

2021-06-18 09:05:13 字數 2688 閱讀 2334

對於標準i/o庫,它們的操作是圍繞流進行的。當用標準i/o庫開啟或建立乙個檔案時,我們已使乙個流與乙個檔案相關聯。

對乙個程序預定義了三個流,並且這三個流可以自動地被程序使用,它們是:標準輸入、標準輸出和標準出錯,對應的檔案指標分別為stdin、stdout和stderr。

為了減少使用read和write的呼叫的次數,標準i/o庫提供了三種型別的緩衝機制,分別為全緩衝、行緩衝和不帶緩衝。

全緩衝:在填滿標準i/o緩衝區後才進行實際i/o操作。

行緩衝:當在輸入和輸出中遇到換行符時,標準i/o庫執行i/o操作。

不帶緩衝:標準i/o庫不對字元進行緩衝儲存。

一般來說,標準出錯是不帶緩衝的,開啟至終端裝置的流是行緩衝的,其他所有流則是全緩衝的。這裡要注意一點的是,全緩衝、行緩衝和不帶緩衝只與流有關,要看流帶不帶緩衝,帶怎樣的緩衝,而與使用哪個標準i/o庫中的函式無關。例如,不能認為使用了fgets函式就認為是行緩衝的。

1、開啟流的函式

file *fopen(const char *restrict pathname, const char *restrict type);

2、判斷出錯或到達檔案尾端的函式

int ferror(file *fp);

int feof(file *fp);

3、一次讀乙個字元的函式

int fgetc(file *fp);

4、一次寫乙個字元的函式

int fputc(int c, file *fp);

5、一次讀一行的函式

char *fgets(char *restrict buf, int n, file *restrict fp);

6、一次寫一行的函式

int fputs(const char *restrict str, file *restrict fp);

7、二進位制i/o函式

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);

其中,size指定每個元素的長度,如sizeof(float)等。nobj指定要寫的元素的個數。

8、定位流的函式

long ftell(file *fp);

int fseek(file *fp, long offset, int whence);

void rewind(file *fp);

int fgetpos(file *restrict fp, fpos_t *restrict pos);

int fsetpos(file *fp, const fpos_t *pos);

9、格式化i/o函式

int printf(const char *restrict format, ...);

int fprintf(file *restrict fp, const char *restrict format, ...);

int sprintf(char *restrict buf, const char *restrict format, ...);

int snprintf(char *restrict buf, size_t n, const char *restrict format, ...);

int scanf(const char *restrict format, ...);

int fscanf(file *restrict fp, const char *restrict format, ...);

int sscanf(const char *restrict buf, const char *restrict format, ...);

10、流與檔案描述符

int fileno(file *fp);

高階i/o裡面一項重要的技術是使用i/o多路轉接。先構造一張有關描述符的列表,然後呼叫乙個函式,知道這些描述符中的乙個已準備好進行i/o時,該函式才返回。

1、select函式

int select(int maxfdp1, fd_set *restrict readfds, fd_set *restrict writefds, fd_set *restrict exceptfds, struct timeval *restrict tvptr);

2、操作描述符集的函式

int fd_isset(int fd, fd_set *fdset);

void fd_clr(int fd, fd_set *fdset);

void fd_set(int fd, fd_set *fdset);

void fd_zero(fd_set *fdset);

注意,宣告了乙個描述符集後,必須用fd_zero清除其所有位,然後在其中設定我們關心的各個位。

3、poll函式

int poll(struct pollfd fdarray, nfds_t nfds, int timeout);

其中struct pollfd{

int fd;

short events;

short revents;

events表示描述符關心什麼事件,revents表示描述符發生了什麼事件。其中比較重要的三個值是pollrdnorm、pollwrnorm、pollerr。

linux程式設計 標準IO

標準io簡介 1.標準io與三種緩衝區關聯 1 全緩衝 通過標準io對檔案 或裝置 進行操作時,通常緩衝區滿之後,才會進行實際的io操作 即寫到核心 對檔案進行操作時通常使用全緩衝。2 行緩衝 通過標準io對檔案 或裝置 進行操作時,通常緩衝區滿之後,或者遇到換行符時,才會進行實際的io操作 即寫到...

Linux標準I O程式設計

標準io的核心物件就是流 file結構體 1.流的開啟函式原型 file fopen const char path,const char mode 函式引數 path 要開啟的檔案路徑及檔名 mode 檔案開啟方式 函式返回值 成功 指向file指標 失敗 nullmode值 取值說明 r開啟唯讀...

Linux程式設計 標準IO(2)

簡單的檔案讀寫例項 include stdiotest.h include include void readlog printf open file success n 單位元組讀取測試 int ichar fgetc plog if eof ichar 位元組回送測試 int iput unge...