Linux系統編程_3_檔案屬性

來源:互聯網
上載者:User

標籤:linux   io   

1.Linux中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;     //最後一次改變時間(指屬性)
};


2.Linux中檔案的類型

一般有7種類型:

普通檔案  目錄檔案   字元裝置檔案  塊裝置檔案  連結檔案  管道檔案  Socket檔案

利用lstat函數來顯示不同檔案類型,注意lstat與stat函數不同,stat函數不能檢測出連結檔案;

測試程式:

|  1 #include <stdio.h>|  2 #include <stdlib.h>|  3 #include <unistd.h>|  4 #include <sys/stat.h>|  5|  6 int main(int argc, char **argv)|  7 {|  8     int i;|  9     char *pInfo;| 10     struct stat stBuf;| 11| 12     if(argc < 2)| 13     {| 14         printf("Usage:./test xxx xxx xxx\n");| 15         exit(-1);| 16     }| 17| 18     for(i=1; i<argc; i++)| 19     {| 20         printf("%s\n", argv[i]);| 21         if(lstat(argv[i], &stBuf) < 0)| 22         {| 23             perror("Open File error");| 24             continue;| 25         }| 26         if(S_ISREG(stBuf.st_mode))| 27             pInfo = "Regular";| 28         else if(S_ISDIR(stBuf.st_mode))| 29             pInfo = "Directory";| 30         else if(S_ISCHR(stBuf.st_mode))| 31             pInfo = "Char special";| 32         else if(S_ISBLK(stBuf.st_mode))| 33             pInfo = "Block special";| 34         else if(S_ISFIFO(stBuf.st_mode))| 35             pInfo = "Fifo";| 36         else if(S_ISLNK(stBuf.st_mode))| 37             pInfo = "Link";| 38         else if(S_ISSOCK(stBuf.st_mode))| 39             pInfo = "Socket";| 40         else| 41             pInfo = "**Unknown Type**";| 42| 43         printf("%s file\n\n", pInfo);| 44     }| 45| 46     return 0;| 47 }

測試命令:./test test /home/ /dev/log /dev/tty /dev/sda /dev/scd0

測試結果:

test
Regular file


/home/
Directory file

/dev/log
Socket file

/dev/tty
Char special file

/dev/sda
Block special file

/dev/scd0
Link file




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.