LoginSignup
2
0

More than 3 years have passed since last update.

C言語でファイルの更新日をナノ秒まで表示する方法

Last updated at Posted at 2019-05-28

※ 2017年の自分の記事を移転しました。

C言語でファイルの更新日時をナノ秒まで表示する方法です。
用途としては、ファイルの定期的な更新確認ですかね。

環境について

・Linuxカーネル2.5.48以上
・ファイルシステム XFS, JFS, Btrfs, ext4
上記以外のファイルシステムは、ナノ秒は0で表示される可能性があります。

ソース

nsec_show.c
#include <stdio.h>
#include <sys/stat.h>
#include <errno.h>
#include <time.h>

int main(int argc, char *argv[])
{
    int i;
    struct stat st;
    char date_str[256];

    /* argc check */
    if (argc != 2) {
        printf("USAGE:%s <FILE PATH>\n", argv[0]);
        return 1;
    }

    /* get stat */
    if (stat(argv[1], &st) != 0) {
        printf("%s\n", strerror(errno));
        return 1;
    }

    /* show */
    strftime(date_str, 255, "%Y%m%d%H%I%M%S", localtime(&st.st_mtime));
    printf("%s.%09ld\n",date_str, st.st_mtim.tv_nsec);

    return 0;
}

動作確認

コンパイル後、実行すると以下のような形で表示されます。

$ gcc nsec_show.c  -o nsec_show
$ ./nsec_show ./nsec_show.c
20170305063637.656058532

ちなみに、lsコマンドで表示されるナノ秒と一致しています。

$ ls ./nsec_show.c --full-time
-rw-rw-r--. 1 miyabi miyabi 581 2017-03-05 06:36:37.656058532 +0900 ./nsec_show.c

参考文献

STAT
CLOCK_GETRES

2
0
2

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
2
0