-1

C、特に Linux でファイル/フォルダのプロパティを取得する方法は?

作成日、最終更新日、isDirectory または isFile、権限、所有権、サイズに関する情報が必要です。

ありがとう。

4

3 に答える 3

4

ほとんどの場合、このstat()関数が必要です。

例:

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);

于 2012-08-01T18:57:31.333 に答える
3

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フィールドを使用してファイル タイプを決定する方法の詳細については、man ページの例を参照してください。POSIXマクロをチェックisDirectory/使用する方法は次のとおりです。isFile

isDirectory = S_ISDIR(statBuf.st_mode);
isFile = S_ISREG(statBuf.st_mode);
于 2012-08-01T19:00:15.290 に答える
1
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);
}
于 2012-08-01T19:05:09.260 に答える