在APUE這本書,第三章與第四章都是在講一些關於文件操作和目錄操作的函數。簡單地說明一下涉及到的函數及其使用。
open函數
原型爲: #include<fcntl.h>
int open(const char *pathname, int oflag,.../*mode_t mode*/);
該函數是用來打開或創建一個文件(記住:是文件,不包括目錄),第三個參數只有當打開文件不存在時(即open函數執行的是創建文件)纔有用,mode_t是用來指定創建文件的用戶ID,組ID,其他用戶的讀寫權限的(注意:還有一個umask函數,真正權限是umask函數和參數mode聯合決定的)。第二個參數表示怎麼打開(以什麼方式打開,讀,寫,讀寫等)。返回值爲打開文件描述符。
creat函數
原型:#include<fcntl.h>
int creat(const char * pathnewname,mode_t mode);
該函數用來創建一個文件。相當於:open(pathnewname,O_WRONLY|O_CREAT|O_TRUNC,mode). 從等價函數open中,可以看出creat函數特點:只能以寫的形式打開該文件,當文件存在時,會將文件內容清除重新開始寫。 返回值也是打開文件的描述符。
close函數
原型:#include<fcntl.h>
int close(int filedes);
關閉函數,成功時返回0,失敗則返回-1
lseek函數
原型:#include<unistd.h>
int lseek(int filedes,off_t offset,int whence);
該函數用來顯示地爲打開一個文件設置偏移量。
whence爲seek_set時表示從起點開始,爲seek_cur表示從當前位置還是,爲seek_end表示從結尾出開始算。返回值爲新的偏移量值。
該函數可以是文件形成空洞。
read函數
原型:#include<unistd.h>
int read(int filedes,void * buf,int bufsize)
該函數用來讀取文件的值。該函數讀取文件的長度爲bufsize,中途遇到空格或者是換行都不會停止的。
write函數
原型:#include<unitsd.h>
int write(int filedes,void * buf,int bufsize)
該函數用來寫文件
dup函數:
原型:#include<unisd.h>
int dup(int filedes); int dup2(int filedes,int filedes1);
該函數用來複制文件描述符。dup是從當前最小的描述符中找,dup2則是將其賦值到filedes1描述符中。最後是他們一起公用文件表項。
fcntl函數
原型:#include<fcntl.h>
int fcntl(int filedes,int cmd,..../*int arg*/)
函數爲改變已打開文件的性質。
stat函數
原型:#include<sys/stat.h>
int stat(const char *restrict pathname,struct stat* restrict buf);
int fstat(int filedes,struct stat* restrict buf);
int lstat(const char *restrict pathname,struct stat* restrict buf);
該函數是返回與此命名的文件有關的信息結構,lstat是返回符號連接的相關信息,stats則是返回符號連接引用文件的信息。
stat結構體信息如下:
struct stat {
mode_t st_mode; /* file type & mode (permissions) */
ino_t st_ino; /* i-node number (serial number) */
dev_t st_dev; /* device number (file system) */
dev_t st_rdev; /* device number for special files */
nlink_t st_nlink; /* number of links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
off_t st_size; /* size in bytes, for regular files */
struct timespec st_atim; /* time of last access */
struct timespec st_mtim; /* time of last modification */
struct timespec st_ctim; /* time of last file status change */
blksize_t st_blksize; /* best I/O block size */
blkcnt_t st_blocks; /* number of disk blocks allocated */
};
umask函數
原型;#include<sys/stat.h>
int umask(mode_t cmask);
該函數用來設置文件模式創建屏蔽字。返回原來的屏蔽字。