unix系統可用的文件IO函數--打開文件,讀取文件,寫文件等。大致用到5個函數:open,read,write,lseek,close。另外不同的緩存器長度對read和write函數有影響。
術語--不帶緩存指的是每個read和write都調用內核中的一個系統調用。
文件描述符:對於內核而言,所有打開文件都由文件文件描述符引用。文件描述符是一個非負整數,當打開一個現存文件或創建一個文件時,內核向進程返回一個文件描述符。慣例中unix shell是文件描述符0與進程的標準輸入結合,文件描述符1與標準輸出相結合,文件描述符2與標準出錯輸出項結合,這些只是管理,與內核無關。在POSIX.1應用程序中,幻數0,1,2被代換成符號常數STDIN_FILENO,STDOUT_FILENO,STDERR_FILENO。這些常數都定義在<unistd.h>中。 文件描述符的範圍是0~OPEN_MAX,早期的Unix版本採用的上限是19(允許每個進程打開20個文件),現在很多系統則將其增加到63個。
OPEN函數:調用open函數可以打開或常見一個文件。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char pathname,int oflag,.../*,mode _tmode*>);
第三個參數寫爲...,這是ANSI C說明餘下草書的數目和類型可以變化的方法。對於open函數而言,僅當創建新文件時菜使用第三個參數。
Linux 常用c函數中這樣定義:
int open( const char * pathname, int flags);
int open( const char * pathname,int flags, mode_t mode);
CREAT函數
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int creat(const char * pathname,mode_t mode)
CLOSE函數
#include<unistd.h>
int close(int filedes);
LSEEK函數
#include<sys/types.h>
#include<unistd.h>
off_t lseek(int filedes,off_t offset,int whence);
對參數offset的解釋與參數whence的值有關:
若whence是SEEK_SET,則將該文件的位移量設置爲距文件開始處offset個字節
若whence是SEEK_CUR,則將該文件的位移量設置爲其當前值加offset,offset可爲正或負
若whence是SEEK_CUR,則將該文件的位移量設置爲其當前值加offset,offset可爲正或負
READ函數
#include<unistd.h>
ssize_t read(int filedes,void * buff,size_t nbytes);
如read成功,則返回讀到的字節數。如已經到達文件的尾端,則返回0.
WRITE函數
#include<unistd.h>
ssize_t write(int filedes,const void * buff,size_t nbytes);
DUP和DUP2函數
#include<unistd.h>
int dup(int filedes);
int dup2(int filedes,int filedes2);
兩個函數的返回:若成功爲新的文件描述符,若出錯返回-1
FCNTL函數
#include<sys/types.h》
#include<unistd.h>
#include<fcntl.h>
int fcntl(int filedes,int cmd,.../* int arg */);
返回:若成功返回則依賴於cmd ,若出錯返回-1
fcntl函數有五種功能:
複製一個現存的描述符(cmd=F_DUPFD)
獲得/設置文件描述符標記(cmd=F_GETFD/F_SETFD)
獲得/設置文件狀態標誌(cmd=F_GETFL/F_SETFL)
獲得/設置異步I/O所有權(cmd=F_GETOWN/F_SETOWN)
獲得/設置記錄鎖(cmd=F_GETLK,F_SETLK/F_SETLKW)