file stat

来源:互联网 发布:javascript获取日期 编辑:程序博客网 时间:2024/06/05 02:01

stat是linux下获取文件状态的一个命令,同时也可以做为函数来获取文件状态。

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

int file_stat(){struct stat stat1;int ret = -1;int file_count = 0;DIR *dir1 = NULL;struct dirent * dirent1 = NULL;memset(&stat1, 0, sizeof(stat1));ret = stat(FILENAME, &stat1); //获取stat结构体状态if(ret < 0){perror("stat");return -1;}if ((stat1.st_mode & S_IFMT) == S_IFREG) //判断是否为文件{   /* Handle regular file */printf("%s is a file.\n", FILENAME);}if(S_ISREG(stat1.st_mode))        //判断是否为文件的另一种写法{printf("%s is a file.\n", FILENAME);}printf("file size=%lu, ino=%lu, uid=%u, mode=%d\n", stat1.st_size, stat1.st_ino, stat1.st_uid, stat1.st_mode);if(access(FILENAME, F_OK) == 0)  //判断文件是否存在{printf("F_OK\n");}if(access(FILENAME, W_OK) == 0)  //是否有写权限{printf("W_OK\n");}if(chmod(FILENAME, S_IWOTH) == 0)   //赋予other 写权限,同时其他组的权限也清空了{printf("chmod S_IWOTH success.\n");}dir1 = opendir("src");  //打开一个目录if(dir1 == NULL){perror("opendir");return -1;}dirent1 = readdir(dir1);while(dirent1 != NULL)   //遍历出所有普通文件{if (dirent1->d_type == DT_REG) //DT_REG 判断是否为普通文件.{file_count++;printf("This is a regular file,file name =%s\n", dirent1->d_name); //DT_DIR      This is a directory.}dirent1 = readdir(dir1);}printf("file_count=%d\n", file_count);return 0;}
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 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           };


原创粉丝点击