Linux中用st mode判斷檔案型別

2021-07-10 20:50:00 字數 1891 閱讀 8160

在linux中,可以利用stat()函式來獲取乙個檔案的狀態

#include #include int stat(const char *file_name, struct stat *buf);
這個函式執行成功返回0,失敗返回-1。取得的檔案狀態存放在buf指標指向的struct stat結構提中, struct stat的定義如下:
struct stat  

;

其中, st_mode這個變數用來判斷檔案型別。

st_mode是用特徵位來表示檔案型別的,特徵位的定義如下:

s_ifmt      0170000     檔案型別的位遮罩

s_ifsock 0140000 socket

s_iflnk 0120000 符號鏈結(symbolic link)

s_ifreg 0100000 一般檔案

s_ifblk 0060000 區塊裝置(block device)

s_ifdir 0040000 目錄

s_ifchr 0020000 字元裝置(character device)

s_ififo 0010000 先進先出(fifo)

s_isuid 0004000 檔案的(set user-id on execution)位

s_isgid 0002000 檔案的(set group-id on execution)位

s_isvtx 0001000 檔案的sticky位

s_irwxu 00700 檔案所有者的遮罩值(即所有權限值)

s_irusr 00400 檔案所有者具可讀取許可權

s_iwusr 00200 檔案所有者具可寫入許可權

s_ixusr 00100 檔案所有者具可執行許可權

s_irwxg 00070 使用者組的遮罩值(即所有權限值)

s_irgrp 00040 使用者組具可讀取許可權

s_iwgrp 00020 使用者組具可寫入許可權

s_ixgrp 00010 使用者組具可執行許可權

s_irwxo 00007 其他使用者的遮罩值(即所有權限值)

s_iroth 00004 其他使用者具可讀取許可權

s_iwoth 00002 其他使用者具可寫入許可權

s_ixoth 00001 其他使用者具可執行許可權

摘自《linux c 函式庫參考手冊》

判斷檔案型別時,用對檔案的st_mode的值與上面給出的值相與,再比較。比如:

#include #include #include int main()

執行結果:

it's a directory.

其實還有乙個簡單的方法,檔案型別在posix中定義了檢查這些型別的巨集定義:

s_islingk(st_mode)      判斷是否位符號鏈結

s_isreg(st_mode) 是否為一般檔案

s_isdir(st_mode) 是否為目錄

s_ischr(st_mode) 是否位字元裝置檔案

s_isblk(s3e) 是否先進先出

s_issock(st_mode) 是否為socket

可以根據這些函式的返回值判斷,如果是,則返回1。(我試了一下,好像是這樣的)

Linux中用st mode判斷檔案型別

在linux中,可以利用stat 函式來獲取乙個檔案的狀態 include include int stat const char file name,struct stat buf 這個函式執行成功返回0,失敗返回 1。取得的檔案狀態存放在buf指標指向的struct stat結構提中,struc...

Linux中用st mode判斷檔案型別

來自 在linux中,可以利用stat 函式來獲取乙個檔案的狀態 cpp view plain copy include include intstat const char file name,struct stat buf 這個函式執行成功返回0,失敗返回 1。取得的檔案狀態存放在buf指標指向...

Linux中用st mode判斷檔案型別

舉報 分類 linux 8 c c 20 在linux中,可以利用stat 函式來獲取乙個檔案的狀態 cpp view plain copy include include int stat const char file name,struct stat buf 這個函式執行成功返回0,失敗返回 ...