(1)stat()函數:通過文件名filename來獲取文件的屬性值
表頭文件: #include <sys/stat.h>
#include <unistd.h>
定義函數: int stat(const char *file_name, struct stat *buf);
函數說明: 通過文件名filename獲取文件信息,並保存在buf所指的結構體stat中
返回值: 執行成功則返回0,失敗返回-1,錯誤代碼存於errno
結構體stat相關的內容:
struct stat {
dev_t st_dev; //文件的設備編號
ino_t st_ino; //節點
mode_t st_mode; //文件的類型和存取的權限(該屬性下面包含很多宏來處理文件的類型以及文件的存取權限)
nlink_t st_nlink; //連到該文件的硬連接數目,剛建立的文件值爲1
uid_t st_uid; //用戶ID
gid_t st_gid; //組ID
dev_t st_rdev; //(設備類型)若此文件爲設備文件,則爲其設備編號
off_t st_size; //文件字節數(文件大小)
unsigned long st_blksize; //塊大小(文件系統的I/O 緩衝區大小)
unsigned long st_blocks; //塊數
time_t st_atime; //最後一次訪問時間
time_t st_mtime; //最後一次修改時間
time_t st_ctime; //最後一次改變時間(指屬性)
};
例子:
#include
<sys/stat.h>
#include <unistd.h>
#include <stdio.h>
int main() {
struct stat buf;
stat("/etc/hosts", &buf);
printf("/etc/hosts file size = %d/n", buf.st_size);
}
(2)fstat()函數:由文件描述符來獲取文件的屬性
相關函數 stat,lstat,chmod,chown,readlink,utime
表頭文件 #include<sys/stat.h>
#include<unistd.h>
定義函數 int fstat(int fildes,struct stat *buf);(stat的說明如上)
函數說明 fstat()用來將參數fildes所指的文件狀態,複製到參數buf所指的
結構中(struct stat)。Fstat()與stat()作用完全相同,不同處在
於傳入的參數爲已打開的文件描述詞。詳細內容請參考stat()。
返回值 執行成功則返回0,失敗返回-1。
(3)lstat()函數:根據文件名來獲取文件的屬性
函數原型:int lstat(const char *path, struct stat *buf);
該函數類似於stat函數,但是當文件是一個符號鏈接的時候lstat返回該符號鏈接的有關信息,而不是由該符號鏈接引用的文件的信息。
(4)access()函數:檢查文件可以執行某種操作
功能描述:
檢查調用進程是否可以對指定的文件執行某種操作。
用法:
#include <unistd.h>
#include <fcntl.h>
int access(const char *pathname, int mode);
參數:
pathname: 需要測試的文件路徑名。
mode: 需要測試的操作模式,可能值是一個或多個R_OK(可讀?), W_OK(可寫?), X_OK(可執行?) 或 F_OK(文件存在?)組合體。
返回說明: 成功執行時,返回0。失敗返回-1,
(5)umask()函數:進程設置文件方式創建屏蔽字,即設置文件的權限,最大的權限是0777
#include
"sys/types.h"
#include "sys/stat.h"
mode_t umask(mode_t cmask);
umask函數爲進程設置文件方式創建屏蔽字。
unix中文件最大訪問權限是0777, 即_rwxrwxrwx.
如果講umask函數設置爲0111, 那麼用0777與0111(umask設置值)取異或操作得0666,即_rw_rw_rw.
當進程使用open或creat創建新文件時, 存取權限就是指定存取權限同0666的位與結果。
譬如下列代碼:
umask(0111);
creat("newfile", 0777);
得到的newfile的存取權限仍然是0666,即0777&0666=0666, 這就是umask的作用, 有點子網掩碼的味道。
(6)chmod()和fchmod()函數:用來更改文件的權限