回答編集履歴
1
長い文章を削除
answer
CHANGED
@@ -10,89 +10,4 @@
|
|
10
10
|
```
|
11
11
|
--format=%wは「ファイルの作成日時だけを表示する」ことを表します。
|
12
12
|
ファイル作成日時が不明であるときは「-」が表示されます。
|
13
|
-
おそらく、CentOSではハイフンが表示されるかと思います。
|
13
|
+
おそらく、CentOSではハイフンが表示されるかと思います。
|
14
|
-
|
15
|
-
ファイル更新日時の場合は、次のように書くことができます。
|
16
|
-
```lang-c
|
17
|
-
#include <stdio.h>
|
18
|
-
#include <time.h>
|
19
|
-
#include <string.h>
|
20
|
-
#include <dirent.h>
|
21
|
-
#include <regex.h>
|
22
|
-
#include <sys/stat.h>
|
23
|
-
|
24
|
-
time_t update_time(char *);
|
25
|
-
void full_path(char *, char *);
|
26
|
-
time_t latest_file(char *, char *);
|
27
|
-
|
28
|
-
int main(int argc, char *argv[])
|
29
|
-
{
|
30
|
-
char *path = argv[1];
|
31
|
-
|
32
|
-
char latest[255];
|
33
|
-
if (latest_file(latest, path) != (time_t)0) {
|
34
|
-
printf("%s が最新のファイルです。\n", latest);
|
35
|
-
}
|
36
|
-
|
37
|
-
return 0;
|
38
|
-
}
|
39
|
-
|
40
|
-
//最終更新日時を数値として取得
|
41
|
-
time_t update_time(char *file)
|
42
|
-
{
|
43
|
-
struct stat buf;
|
44
|
-
if (stat(file, &buf) == 0) {
|
45
|
-
return buf.st_mtime;
|
46
|
-
} else {
|
47
|
-
return (time_t)0;
|
48
|
-
}
|
49
|
-
}
|
50
|
-
|
51
|
-
//パスとファイル名を連結する
|
52
|
-
void full_path(char *path, char *name)
|
53
|
-
{
|
54
|
-
regex_t preg;
|
55
|
-
size_t nmatch = 1;
|
56
|
-
regmatch_t pmatch[nmatch];
|
57
|
-
|
58
|
-
regcomp(&preg, "/$", REG_EXTENDED);
|
59
|
-
|
60
|
-
if (regexec(&preg, path, nmatch, pmatch, 0) != 0) {
|
61
|
-
strcat(path, "/");
|
62
|
-
}
|
63
|
-
|
64
|
-
strcat(path, name);
|
65
|
-
}
|
66
|
-
|
67
|
-
//最終更新日時の最も新しいファイルの名前を変数に格納
|
68
|
-
time_t latest_file(char *latest, char *path)
|
69
|
-
{
|
70
|
-
char full[255];
|
71
|
-
time_t max = (time_t)0;
|
72
|
-
|
73
|
-
DIR *dir = opendir(path);
|
74
|
-
struct dirent *dp;
|
75
|
-
|
76
|
-
for (dp = readdir(dir); dp != NULL; dp = readdir(dir))
|
77
|
-
{
|
78
|
-
if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0) {
|
79
|
-
continue;
|
80
|
-
}
|
81
|
-
|
82
|
-
strcpy(full, path);
|
83
|
-
full_path(full, dp->d_name);
|
84
|
-
|
85
|
-
int temp = update_time(full);
|
86
|
-
if (temp > max) {
|
87
|
-
max = temp;
|
88
|
-
strcpy(latest, dp->d_name);
|
89
|
-
}
|
90
|
-
}
|
91
|
-
|
92
|
-
closedir(dir);
|
93
|
-
return max;
|
94
|
-
}
|
95
|
-
```
|
96
|
-
stat構造体のst_mtimeメンバには、最終更新日時を表す数値が入っています。
|
97
|
-
この数値は、1970年1月1日午前0時0分0秒からの経過秒数(UNIX時間)を表すので、大きな数値ほど最新のファイルということになります。
|
98
|
-
すべてのファイルのUNIX時間を調べることで、最新のファイルを知ることができます。
|