获取文件或目录的属性 stat 函数

头文件:  <sys/types.h>   <sys/stat.h>   <unistd.h>

int stat(const char *path, struct stat *buf);   成功返回0 ,失败返回-1
int fstat(int fd, struct stat *buf);
int lstat(const char *path, struct stat *buf);  //使用类似,其中fstat 传递的是文件描述符

 

例子:通过stat函数获取文件属性,存放在传递形参的结构体中 (通过 man 2 stat 查看函数使用信息)

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, const char *argv[])
{
//    struct stat buf;
    //指针只是,一个指向的指针,并没有实际的结构体空间
    struct stat *sbuf = (struct stat *)malloc(sizeof(struct stat));//使用结构体指针要为其分配空间
    int ret = 0;
//    ret = stat(argv[1],&buf);
    ret = stat(argv[1],sbuf);
    if(ret == -1)
    {
        perror("fail : ");
        exit(1);
    }

    if(S_ISREG(sbuf->st_mode)) //测试是否为普通文件
//    if(S_ISREG(buf.st_mode))
    {
        printf("-
");
    }
    if(S_IWUSR & sbuf->st_mode)
//    if(S_IWUSR & buf.st_mode)
    {
        printf("w
");
    }

    return 0;
}

测试:

关于struct stat *buf结构体

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 file system I/O */
  blkcnt_t st_blocks; /* number of 512B 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 */
};

其中  st_mode 成员信息

原文地址:https://www.cnblogs.com/electronic/p/10920035.html