2012-06-30 61 views
2

我正在使用C語言在Linux計算機上工作,該計算機顯示作爲參數提供給程序的文件的文件類型。該程序需要確定文件是否是以下任何一個:目錄,設備,(常規)文件,鏈接,套接字或fifo。我不確定如何確定文件類型。在C中確定文件類型

這裏是我的代碼迄今(不要太多):

int 
main(int argc, char **argv) 
{ 
    if(argc == 1)  /* default: current directory */ 
     puts("Directory"); 
    else 
     while(--argc > 0) 
      determine_ftype(*++argv); 

    return 0; 
} 

謝謝!

回答

10

使用POSIX stat函數並讀取函數返回的結構struct statst_mode字段。

stat功能:

http://pubs.opengroup.org/onlinepubs/7908799/xsh/stat.html

結構struct stat類型:

http://pubs.opengroup.org/onlinepubs/7908799/xsh/sysstat.h.html

對於glibc的,也可以讀出的glibc手冊的部分14.9.3 Testing the Type of a File

http://www.gnu.org/software/libc/manual/html_node/Testing-File-Type.html

+0

所以,基本上我會使用st_mode並通過一系列if語句來確定文件類型是什麼。正確? – Jordan

+0

@JordanCarney準確無誤。 – ouah

+0

夠簡單。謝謝! – Jordan