「C」ファイルの状態を取得する
C でファイルの状態を取得するサンプル書いてみたので、メモしておきます。
以下の sys_stat を使ってます。
・fstatat
http://pubs.opengroup.org/onlinepubs/9699919799/functions/stat.html
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/stat.h> void main() { char *path = "/home/ubuntu/workspace/filestat/test"; struct stat buf; if(stat(path, &buf) != 0) { perror("stat"); exit(1); } printf("uid : %d\n", buf.st_uid); printf("size : %d\n", (int)buf.st_size); printf("last modify time : %s\n", ctime(&buf.st_mtime)); }
これ使えば簡単なファイルの監視とかできますね。
例えば、ファイルサイズの変更で監視するのであれば、以下の感じで。
void sizeMonitoring() { char *path = "/home/ubuntu/workspace/filestat/test"; struct stat buf; int size1, size2; if(stat(path, &buf) != 0) { perror("stat"); exit(1); } size1 = (int)buf.st_size; int i; for(i = 0; i < 5; i++) { if(stat(path, &buf) != 0) { perror("stat"); exit(1); } size2 = (int)buf.st_size; if(size1 == size2) { printf("not change size : %d\n", size2); } else { printf("change size : %d -> %d\n", size1, size2); size1 = size2; } sleep(5); } }
※ 特にループ回数とかに意味はありません・・・
以上です。