【问题标题】:How to read file/folder properties in Linux?如何在 Linux 中读取文件/文件夹属性?
【发布时间】:2012-08-01 18:55:13
【问题描述】:

如何在 C 中检索文件/文件夹的属性,尤其是在 Linux 中?

我需要有关创建日期、上次修改时间、isDirectory 或 isFile、权限、所有权和大小的信息。

谢谢。

【问题讨论】:

标签: c linux


【解决方案1】:

您很可能需要stat() function.

例子:

struct stat attr;
stat("/home/crazyfffan/foo.txt", &attr);

printf("Size: %u\n", (unsigned)attr.st_size);
printf("Permissions: %o\n", (int)attr.st_mode & 07777);
printf("Is directory? %d\n", attr.st_mode & ST_ISDIR);

等等

【讨论】:

  • 最后一行没有编译,我用的是:printf("Is directory? %d\n", S_ISDIR(attr.st_mode));
【解决方案2】:

使用stat 系统调用。 man 2 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 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 字段确定文件类型的详细信息;以下是使用 POSIX 宏检查 isDirectory/isFile 的方法:

isDirectory = S_ISDIR(statBuf.st_mode);
isFile = S_ISREG(statBuf.st_mode);

【讨论】:

    【解决方案3】:
    struct stat file_stats;    
    
    fd = open(filename, O_RDONLY);
    if (fd == -1) {
        exit(-1);
    }
    
    if (fstat(fd, &file_stats) < 0) {
        exit(-1);
    }
    if (S_ISDIR(file_stats.st_mode)) {
          printf("It is dir\n");
    } else {
        snprintf(msg, PATH_MAX, "%lld, %ld, %o, %d, %d, %d, %lld, %ld, %ld, %ld, %ld, %ld,
        %ld\n",
                file_stats.st_dev,
                file_stats.st_ino,
                file_stats.st_mode,
                file_stats.st_nlink,
                file_stats.st_uid,
                file_stats.st_gid,
                file_stats.st_rdev,
                file_stats.st_size,
                file_stats.st_blksize,
                file_stats.st_blocks,
                file_stats.st_atime,
                file_stats.st_mtime,
                file_stats.st_ctime);
    }
    

    【讨论】:

    • 没有对这些字段的用途进行一些描述,这并没有它应有的帮助。
    猜你喜欢
    • 2018-11-02
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    相关资源
    最近更新 更多