4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Cでファイルの情報を取得して表示する

Last updated at Posted at 2015-04-22

ファイル情報?

いろいろありますが、今回はman fstatで取れる値を表示するまで。
とても短いのにprintfするまで(型合わせが)面倒だったので自分用メモ。

構造体

fstatを使うとこんな感じの値が取れるそうです。$ man fstat で見れます。

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 */
    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 */
};

みんな符号付きだったり符号なしだったりする整数なんですが、printfする際には型を合わせないと警告が出続けたり、あまり警告を無視すると痛い目見たりします。

printfする

# include <sys/stat.h>
# include <unistd.h>
# include <time.h>
# include <stdio.h>

int main(int argc, char** argv) {
  struct stat buf;
  int rebt = stat(argv[1], &buf);
  printf("st_dev: %lu\n"
         "st_ino: %ld\n"
         "st_mode: %u\n"
         "st_nlink: %lu\n"
         "st_uid: %u\n"
         "st_gid: %d\n"
         "st_rdev: %lu\n"
         "st_size: %ld\n"
         "st_blksize: %ld\n"
         "st_blocks: %ld\n"
         "st_atime: %ld\n"
         "st_mtime: %ld\n"
         "st_ctime: %ld\n",
         buf.st_dev,
         buf.st_ino,
         buf.st_mode,
         buf.st_nlink,
         buf.st_uid,
         buf.st_gid,
         buf.st_rdev,
         buf.st_size,
         buf.st_blksize,
         buf.st_blocks,
         buf.st_atime,
         buf.st_mtime,
         buf.st_ctime);
}

こんな感じで表示できます。

$ ./a.out hoge.cc
st_dev: 2049
st_ino: 17043777
st_mode: 33188
st_nlink: 1
st_uid: 1000
st_gid: 1000
st_rdev: 0
st_size: 802
st_blksize: 4096
st_blocks: 8
st_atime: 1429718442
st_mtime: 1429718439
st_ctime: 1429718439
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?