天天看點

《APUE》讀書筆記—第五章标準I/O庫

  标準i/o庫是iso c的标準,在很多作業系統上面都實作。unix檔案i/o函數都是針對檔案描述符的,當打開一個檔案的時候,傳回該檔案描述符用于後續的i/o操作。而對于标準i/o庫,操作則是圍繞流進行,當用标準i/o庫打開或者建立一個檔案時,使得一個流與檔案相關聯。标準i/o庫使用了緩沖技術,使用緩沖的目的是盡可能減少使用read和write調用次數,但是效率不高。每次進行讀寫時候需要複制兩次資料。第一次是在核心和标準i/o緩沖之間(調用read和write),第二次是在标準i/o緩沖區和使用者程式中的行緩沖區之間。提供了三種類型的緩沖:全緩沖、行緩沖和不帶緩沖。标準i/o預定義三個檔案指針stdin、stdout和stderr。

  當一個流最初被建立的時候,沒有定向。可以用fwide函數設定流的定向,freopen函數清除一個流的定向。采用setbuf和setvbuf函數更改緩沖區類型,fflush函數沖洗一個流。

int fwide(file *stream, int mode); //若流是寬字元定向則傳回正值,若是位元組定向則傳回負值,如實為定向的則傳回0

void setbuf(file *stream, char *buf);

int setvbuf(file *stream, char *buf, int mode, size_t size);   

_ionbf  unbuffered  _iolbf  line buffered  _iofbf  fully buffered

int fflush(file *fp);

i/o操作函數:

file *fopen(const char *path, const char *mode);  //打開一個指定的檔案

file *fdopen(int fd, const char *mode);  //擷取一個現有的檔案描述符,使得一個i/o流與該描述符先結合,常用于由建立管道和網絡通信通道函數傳回的描述符。

file *freopen(const char *path, const char *mode, file *stream);//在一個指定的流上打開一個指定的檔案

int fclose(file* fp);

一次讀取一個字元

int fgetc(file *stream);

int getc(file *stream);

int getchar(void);

一次讀取一行

char *fgets(char *s, int size, file *stream);

char *gets(char *s);

一次寫一個字元

int fputc(int c, file *stream);

int putc(int c, file *stream);

int putchar(int c);

一次寫入一行

int fputs(const char *s, file *stream);

int puts(const char *s);

針對二進制i/o,一般是結構體類型

size_t fread(void *ptr, size_t size, size_t nmembfile *" stream );

size_t fwrite(const void *ptr, size_t size, size_t nmemb,file *stream);

檔案定位函數

int fseek(file *stream, long offset, int whence); //設定檔案的位置

long ftell(file *stream);  //傳回目前檔案的位置訓示

void rewind(file *stream);  //将一個流的位置設定到檔案的開始位置

int fgetpos(file *stream, fpos_t *pos);  

int fsetpos(file *stream, fpos_t *pos); 

fgetpos函數将檔案訓示器的目前值存入有pos指向的對象中,在以後調用fsetpos時,可以使用此值将流重新定位到該位置。

格式化i/o:

#include <stdio.h>

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

int fprintf(file *stream, const char *format, ...);  //寫入到檔案

int sprintf(char *str, const char *format, ...);  //格式化字元串,可以将其他類型轉換為字元串

int snprintf(char *str, size_t size, const char *format, ...);

#include <stdarg.h>

int vprintf(const char *format, va_list ap);

int vfprintf(file *stream, const char *format, va_list ap);

int vsprintf(char *str, const char *format, va_list ap);

int vsnprintf(char *str, size_t size, const char *format, va_list ap);

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

int fscanf(file *stream, const char *format, ...);  //從檔案中讀取

int sscanf(const char *str, const char *format, ...);  //可以提取字元串内容,遇到空格停止

int vscanf(const char *format, va_list ap);

int vsscanf(const char *str, const char *format, va_list ap);

int vfscanf(file *stream, const char *format, va_list ap);

在unix系統中,标準i/o庫最終都要調用檔案i/o,每個标準i/o流都有一個與其相關聯的檔案描述符。一個流可以通過調用fileno函數擷取其描述符。

int fileno(file *fp)  //在調用dup和fcntl函數的時候用到

臨時檔案建立函數tmpnam和tepfile

char *tmpnam(char *s);

file *tmpfile(void);

針對标準i/o寫個程式進行練習,程式如下:

《APUE》讀書筆記—第五章标準I/O庫
《APUE》讀書筆記—第五章标準I/O庫

測試結果如下:

《APUE》讀書筆記—第五章标準I/O庫