struct stat 作用

stat,lstat,fstat1 函數都是獲取文件(普通文件,目錄,管道,socket,字符,塊()的屬性。函數原型#include <sys/stat.h>

int stat(const char *restrict pathname, struct stat *restrict buf);提供文件名字,獲取文件對應屬性。

int fstat(int filedes, struct stat *buf);通過文件描述符獲取文件對應的屬性。

int lstat(const char *restrict pathname, struct stat *restrict buf);連接文件描述命,獲取文件屬性。2 文件對應的屬性

struct stat {

        mode_t     st_mode;       //文件對應的模式,文件,目錄等

        ino_t      st_ino;       //inode節點號

        dev_t      st_dev;        //設備號碼

        dev_t      st_rdev;       //特殊設備號碼

        nlink_t    st_nlink;      //文件的連接數

        uid_t      st_uid;        //文件所有者

        gid_t      st_gid;        //文件所有者對應的組

        off_t      st_size;       //普通文件,對應的文件字節數

        time_t     st_atime;      //文件最後被訪問的時間

        time_t     st_mtime;      //文件內容最後被修改的時間

        time_t     st_ctime;      //文件狀態改變時間

        blksize_t st_blksize;    //文件內容對應的塊大小

        blkcnt_t   st_blocks;     //偉建內容對應的塊數量

      };

----------------------------------------------------------------------------------------

#include <unsitd.h>

#inlcude <sys/stat.h>

#include <sys/types.h>

int fstat(int filedes,struct stat *buf);

int stat(const char *path,struct stat *buf);

int lstat(const char *path,struct stat *buf);

這三個系統調用都可以返回指定文件的狀態信息,這些信息被寫到結構struct stat的緩衝區中。通過分析這個結構可以獲得指定文件的信息。

void report(struct stat *ptr)

{

     printf("The major device no is:%d\n",major(ptr->st_dev));//主設備號

     printf("The minor device no is:%d\n",minor(ptr->st_dev));//從設備號

     printf("The file's node number is:%d\n",ptr->st_ino);//文件節點號

     printf("The file's access mode is:%d\n",ptr->st_mode);//文件的訪問模式

     printf("The file's hard link number is:%d\n",ptr->st_nlink);//文件的硬鏈接數目

     printf("The file's user id is:%d\n",ptr->uid);//文件擁有者的ID

     printf("The file's group id is:%d\n",ptr->gid);//文件的組ID

     printf("The file's size is:%d\n",ptr->st_size);//文件的大小

     printf("The block size is:%d\n",ptr->blksize);//文件佔用的塊數量

     printf("The number of allocated blocks is:%d\n",ptr->st_blocks);//文件分配塊數量

     struct tm*accesstime,*lmodifytime,*lchangetime;//訪問時間,修改時間,最後一個改變時間(屬性)

     accesstime=localtime(&(ptr->st_atime));

     accesstime=localtime(&(ptr->st_mtime));

     accesstime=localtime(&(ptr->st_ctime));

     printf("The last access time is: %d::%d::%d\n",accesstime->hour,accesstime->min,accesstime->sec);

     printf("The last modify time is:%d::%d::%d\n",lmodifytime->hour,lmodifytime->min,lmodifytime->sec);

     printf("The last change time is:%d::%d::%d\n",lchangetime->hour,lchangetime->min,lchangetime->sec);

}

結構time_t可用用localtime轉換成tm結構,獲得本地時間。

學習交流進步未來

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章