Linux中stat函数和stat命令怎么用

发布时间:2022-01-25 09:09:11 作者:小新
来源:亿速云 阅读:125

小编给大家分享一下Linux中stat函数和stat命令怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

Linux文件里的【inode = index node】解释:要理解inode必须了解磁盘和【目录项】,inode实际是连接【目录项】和磁盘的中间物质。

Linux中stat函数和stat命令怎么用

Linux中stat函数和stat命令怎么用

1,stat函数:取得指定文件的文件属性,文件属性存储在结构体stat里。

#include #include #include int stat(const char *pathname, struct stat *statbuf);
int fstat(int fd, struct stat *statbuf);
int lstat(const char *pathname, struct stat *statbuf);

struct stat 结构体:

struct stat {
               dev_t     st_dev;         /* ID of device containing file */
               ino_t     st_ino;         /* Inode number */
               mode_t    st_mode;        /* File type and mode */
               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;     /* Block size for filesystem I/O */
               blkcnt_t  st_blocks;      /* Number of 512B blocks allocated */

               /* Since Linux 2.6, the kernel supports nanosecond
                  precision for the following timestamp fields.
                  For the details before Linux 2.6, see NOTES. */

               struct timespec st_atim;  /* Time of last access */
               struct timespec st_mtim;  /* Time of last modification */
               struct timespec st_ctim;  /* Time of last status change */

           #define st_atime st_atim.tv_sec      /* Backward compatibility */
           #define st_mtime st_mtim.tv_sec
           #define st_ctime st_ctim.tv_sec
           };

Linux中stat函数和stat命令怎么用

文件类型的宏如下(下面的数字是8进制):

判断文件类型的函数,返回true,false       
   S_ISREG(stat.st_mode)  is it a regular file?
   S_ISDIR(stat.st_mode)  directory?
   S_ISCHR(stat.st_mode)  character device?
   S_ISBLK(stat.st_mode)  block device?
   S_ISFIFO(m) FIFO (named pipe)?
   S_ISLNK(stat.st_mode)  symbolic link?  (Not in POSIX.1-1996.)
   S_ISSOCK(stat.st_mode) socket?  (Not in POSIX.1-1996.)

文件权限的宏如下:

       S_ISUID     04000   set-user-ID bit
       S_ISGID     02000   set-group-ID bit (see below)
       S_ISVTX     01000   sticky bit (see below)

       S_IRWXU     00700   owner has read, write, and execute permission
       S_IRUSR     00400   owner has read permission
       S_IWUSR     00200   owner has write permission
       S_IXUSR     00100   owner has execute permission

       S_IRWXG     00070   group has read, write, and execute permission
       S_IRGRP     00040   group has read permission
       S_IWGRP     00020   group has write permission
       S_IXGRP     00010   group has execute permission

       S_IRWXO     00007   others (not in group) have read,  write,  and
                           execute permission
       S_IROTH     00004   others have read permission
       S_IWOTH     00002   others have write permission
       S_IXOTH     00001   others have execute permission

pathname:文件名

返回值:0代表成功;-1代表失败,并设置error

例子:statbuf是结构体stat,可以看出来st_mode是个10进制的数字。

Linux中stat函数和stat命令怎么用

Linux中stat函数和stat命令怎么用

stat命令,是stat函数对应,执行结果如下:

ys@ys-VirtualBox:~/lianxi1$ stat hello
  File: hello
  Size: 11          Blocks: 8          IO Block: 4096   regular file
Device: 801h/2049d  Inode: 3801352     Links: 2
Access: (0764/-rwxrw-r--)  Uid: ( 1000/      ys)   Gid: ( 1000/      ys)
Access: 2019-04-24 17:02:39.199461489 +0800
Modify: 2019-04-24 16:54:16.407461489 +0800
Change: 2019-04-24 17:03:44.927461489 +0800

2,getpwuid函数:返回/etc/passwd文件里指定uid的行,把这一行的信息放入结构体passwd中。虽然返回值是指针,但不需要调用free函数。

#include #include struct passwd *getpwnam(const char *name);
struct passwd *getpwuid(uid_t uid);

struct passwd {
  char   *pw_name;       /* username */
  char   *pw_passwd;     /* user password */
  uid_t   pw_uid;        /* user ID */
  gid_t   pw_gid;        /* group ID */
  char   *pw_gecos;      /* user information */
  char   *pw_dir;        /* home directory */
  char   *pw_shell;      /* shell program */
};

3,getgrgid函数:返回/etc/group文件里指定gid的行,把这一行的信息放入结构体group中。虽然返回值是指针,但不需要调用free函数。

#include #include struct group *getgrnam(const char *name);
struct group *getgrgid(gid_t gid);

struct group {
  char   *gr_name;        /* group name */
  char   *gr_passwd;      /* group password */
  gid_t   gr_gid;         /* group ID */
  char  **gr_mem;         /* NULL-terminated array of pointers
                             to names of group members */
};

4,localtime函数:传入从stat函数里得到的st_mtim.tv_sec(当前时间到1970.1.1 00:00:00的秒数),得到结构体tm。虽然返回值是指针,但不需要调用free函数。

#include struct tm *localtime(const time_t *timep);
struct tm {
  int tm_sec;    /* Seconds (0-60) */
  int tm_min;    /* Minutes (0-59) */
  int tm_hour;   /* Hours (0-23) */
  int tm_mday;   /* Day of the month (1-31) */
  int tm_mon;    /* Month (0-11) */
  int tm_year;   /* Year - 1900 */
  int tm_wday;   /* Day of the week (0-6, Sunday = 0) */
  int tm_yday;   /* Day in the year (0-365, 1 Jan = 0) */
  int tm_isdst;  /* Daylight saving time */
};

5,lstat函数:stat碰到软链接,会追述到源文件,穿透;lstat并不会穿透。

例子:模仿ls -l 文件

#include #include #include #include #include #include //getpwuid
#include #include //localtime
#include //getgrgid

int main(int argc, char* argv[]){

  struct stat sbuf;
  //stat(argv[1], &sbuf);
  lstat(argv[1], &sbuf);

  char str[11] = {0};
  memset(str, '-', (sizeof str - 1));
    
  //文件类型
  if(S_ISREG(sbuf.st_mode))  str[0] = '-';
  if(S_ISDIR(sbuf.st_mode))  str[0] = 'd';
  if(S_ISCHR(sbuf.st_mode))  str[0] = 'c';
  if(S_ISBLK(sbuf.st_mode))  str[0] = 'b';
  if(S_ISFIFO(sbuf.st_mode)) str[0] = 'p';
  if(S_ISLNK(sbuf.st_mode))  str[0] = 'l';
  if(S_ISSOCK(sbuf.st_mode)) str[0] = 's';

  //本用户的文件权限
  if(sbuf.st_mode & S_IRUSR) str[1] = 'r';
  if(sbuf.st_mode & S_IWUSR) str[2] = 'w';
  if(sbuf.st_mode & S_IXUSR) str[3] = 'x';
  
  //本用户的组的文件权限
  if(sbuf.st_mode & S_IRGRP) str[4] = 'r';
  if(sbuf.st_mode & S_IWGRP) str[5] = 'w';
  if(sbuf.st_mode & S_IXGRP) str[6] = 'x';
  
  //其他用户的文件权限
  if(sbuf.st_mode & S_IROTH) str[7] = 'r';
  if(sbuf.st_mode & S_IWOTH) str[8] = 'w';
  if(sbuf.st_mode & S_IXOTH) str[9] = 'x';

  char ymd[20] = {0};
  //取得日期和时间
  struct tm* tm = localtime(&sbuf.st_atim.tv_sec);
  sprintf(ymd, "%2d月  %2d %02d:%02d", tm->tm_mon + 1, tm->tm_mday,
      tm->tm_hour + 1,tm->tm_sec);
    
  //-rw-r--r-- 1 ys ys 134 4月  25 09:21 st2.c
  printf("%s %ld %s %s %ld %s %s\n", str, sbuf.st_nlink,
     getpwuid(sbuf.st_uid)->pw_name, getgrgid(sbuf.st_gid)->gr_name,
     sbuf.st_size, ymd, argv[1]);
  return 0;
}

6,access函数:判断调用程序的用户对于指定文件的权限(可读?可写?可执行?)

#include int access(const char *pathname, int mode);

例子:

#include #include //access

int main(int argc, char* argv[]){
  if(access(argv[1], R_OK) == 0)
    printf("read ok\n");
  if(access(argv[1], W_OK) == 0)
    printf("write ok\n");
  if(access(argv[1], X_OK) == 0)
    printf("exe ok\n");
  if(access(argv[1], F_OK) == 0)
    printf("exists\n");
}

7,truncate函数:截断文件和扩展文件的大小

#include #include int truncate(const char *path, off_t length);

8,link函数:创建硬链接

#include int link(const char *oldpath, const char *newpath);

返回值:成功返回0,失败返回-1,并设置errno。

9,symlink函数:创建软链接

#include int symlink(const char *target, const char *linkpath);

返回值:成功返回0,失败返回-1,并设置errno。

10,readlink函数:找到软链接对应的实际文件,把文件的名字放入buf里。注意:硬链接不行。

#include ssize_t readlink(const char *pathname, char *buf, size_t bufsiz);

返回值:成功返回写入buf的字节数,失败返回-1,并设置errno。

11,unlink函数:删除软硬链接,也可以删除文件。

#include int unlink(const char *pathname);

返回值:成功返回0,失败返回-1,并设置errno。

有个特殊用法:下面的open代码想要创建hello文件,然后直接用unlink删除,但是能写入成功,ret是大于0的,程序执行完,发现没有做成hello文件。

结论:当执行unlink后,计数为0后,但,发现别的进程还引用这个文件,这个时间点,unlink不会删除这个文件,等这个进程结束后,再删除,所以下面的write代码能够写入成功。
利用这个特点可以实现:在线观看视频时,实际是把视频文件下载到了本地(然后代码里,使用unlink),看完后视频文件的计数为0,就自动删除了,不怕视频被泄露出去。

#include #include #include #include #include int main(){
  int fd = open("hello", O_WRONLY | O_CREAT, 0666);
  unlink("hello");
  int ret = write(fd, "aaa", 4);
  if(ret > 0){
    printf("write OK\n");
  }
  
}

12,chown函数:改变文件的所属用户和组

#include int chown(const char *pathname, uid_t owner, gid_t group);

13,rename函数:重命名

#include int rename(const char *oldpath, const char *newpath);

14,getcwd函数:获得当前工作的目录

#include char *getcwd(char *buf, size_t size);

15,chdir函数:改变进程的工作目录

#include int chdir(const char *path);

16,mkdir函数:创建目录

#include #include int mkdir(const char *pathname, mode_t mode);

17,rmdir函数:删除目录,目录必须是空目录,也就是里面没有任何文件。

#include int rmdir(const char *pathname);

18,opendir函数:打开目录

#include #include DIR *opendir(const char *name);

19,readdir函数:读目录

#include struct dirent *readdir(DIR *dirp);

struct dirent {
  ino_t          d_ino;       /* Inode number */
  off_t          d_off;       /* Not an offset; see below */
  unsigned short d_reclen;    /* Length of this record */
  unsigned char  d_type;      /* Type of file; not supported
                                 by all filesystem types */
  char           d_name[256]; /* Null-terminated filename */
};

20,closedir函数:关闭目录

#include #include int closedir(DIR *dirp);

以上是“Linux中stat函数和stat命令怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. Linux中stat命令的使用
  2. stat函数

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

linux stat

上一篇:Java使用list集合remove需要注意的事项有哪些

下一篇:Linux下如何安装SVN服务端

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》