獲取文件信息

#include <sys/types.h>

#include <sys/stat.h>

#include <unistd.h>

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

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

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

 

stat的定義

          struct stat {

              dev_t     st_dev;     /* ID of device containing file */

              ino_t     st_ino;     /* inode number */

              mode_t    st_mode;    /* protection */

              nlink_t   st_nlink;   /* number of hard links */

              uid_t     st_uid;     /* user ID of owner */

              gid_t     st_gid;     /* group ID of owner */

              dev_t     st_rdev;    /* device ID (if special file) */

              off_t     st_size;    /* total size, in bytes */

              blksize_t st_blksize; /* blocksize for filesystem I/O */

              blkcnt_t  st_blocks;  /* number of blocks allocated */

              time_t    st_atime;   /* time of last access */

              time_t    st_mtime;   /* time of last modification */

              time_t    st_ctime;   /* time of last status change */

          };

文件類型

              S_ISREG(m)  is it a regular file?

              S_ISDIR(m)  directory?

              S_ISCHR(m)  character device?

              S_ISBLK(m)  block device?

              S_ISFIFO(m) FIFO (named pipe)?

              S_ISLNK(m)  symbolic link? (Not in POSIX.1-1996.)

              S_ISSOCK(m) socket? (Not in POSIX.1-1996.)

函數說明 fstat()用來將參數fildes所指的文件狀態,複製到參數buf所指的

結構中(struct stat)fstat()stat()作用完全相同,不同處在

於傳入的參數爲已打開的文件描述詞。詳細內容請參考stat()

返回值 執行成功則返回0,失敗返回-1,錯誤代碼存於errno

設備號是16位的二進制,高八位主設備號(int)((unsigned short )a>>8),第八位次設備號(int)((unsigned short )a&0xFF)

主設備號決定是用什麼驅動程序訪問設備,次設備號區分某一設備的各個類別如:

/dev/sda1

/dev/sda2

df命令訪問某文件分區

獲取某文件的文件狀態

int main(int arg, char *args[])

{

if (arg < 2)

{

printf("open file error");

return -1;

}

int fd = open(args[1], O_RDONLY);

if (fd == -1)

{

printf("error occur %s\n", strerror(errno));

} else

{

printf("the fd = %d\n", fd);

struct stat tmp;

int i = stat(args[1],&tmp);

if(i==-1)

{

printf("error\n");

close(fd);

return -1;

}

else

{

if(S_ISREG(tmp.st_mode))

printf("S_ISREG\n");

printf("%d\n",S_ISDIR(tmp.st_mode));

printf("%d\n",tmp.st_uid);

}

close(fd);

}

return 0;

}

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