回答編集履歴

1

長い文章を削除

2015/04/29 03:34

投稿

penguinshunya
penguinshunya

スコア140

test CHANGED
@@ -23,173 +23,3 @@
23
23
  ファイル作成日時が不明であるときは「-」が表示されます。
24
24
 
25
25
  おそらく、CentOSではハイフンが表示されるかと思います。
26
-
27
-
28
-
29
- ファイル更新日時の場合は、次のように書くことができます。
30
-
31
- ```lang-c
32
-
33
- #include <stdio.h>
34
-
35
- #include <time.h>
36
-
37
- #include <string.h>
38
-
39
- #include <dirent.h>
40
-
41
- #include <regex.h>
42
-
43
- #include <sys/stat.h>
44
-
45
-
46
-
47
- time_t update_time(char *);
48
-
49
- void full_path(char *, char *);
50
-
51
- time_t latest_file(char *, char *);
52
-
53
-
54
-
55
- int main(int argc, char *argv[])
56
-
57
- {
58
-
59
- char *path = argv[1];
60
-
61
-
62
-
63
- char latest[255];
64
-
65
- if (latest_file(latest, path) != (time_t)0) {
66
-
67
- printf("%s が最新のファイルです。\n", latest);
68
-
69
- }
70
-
71
-
72
-
73
- return 0;
74
-
75
- }
76
-
77
-
78
-
79
- //最終更新日時を数値として取得
80
-
81
- time_t update_time(char *file)
82
-
83
- {
84
-
85
- struct stat buf;
86
-
87
- if (stat(file, &buf) == 0) {
88
-
89
- return buf.st_mtime;
90
-
91
- } else {
92
-
93
- return (time_t)0;
94
-
95
- }
96
-
97
- }
98
-
99
-
100
-
101
- //パスとファイル名を連結する
102
-
103
- void full_path(char *path, char *name)
104
-
105
- {
106
-
107
- regex_t preg;
108
-
109
- size_t nmatch = 1;
110
-
111
- regmatch_t pmatch[nmatch];
112
-
113
-
114
-
115
- regcomp(&preg, "/$", REG_EXTENDED);
116
-
117
-
118
-
119
- if (regexec(&preg, path, nmatch, pmatch, 0) != 0) {
120
-
121
- strcat(path, "/");
122
-
123
- }
124
-
125
-
126
-
127
- strcat(path, name);
128
-
129
- }
130
-
131
-
132
-
133
- //最終更新日時の最も新しいファイルの名前を変数に格納
134
-
135
- time_t latest_file(char *latest, char *path)
136
-
137
- {
138
-
139
- char full[255];
140
-
141
- time_t max = (time_t)0;
142
-
143
-
144
-
145
- DIR *dir = opendir(path);
146
-
147
- struct dirent *dp;
148
-
149
-
150
-
151
- for (dp = readdir(dir); dp != NULL; dp = readdir(dir))
152
-
153
- {
154
-
155
- if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0) {
156
-
157
- continue;
158
-
159
- }
160
-
161
-
162
-
163
- strcpy(full, path);
164
-
165
- full_path(full, dp->d_name);
166
-
167
-
168
-
169
- int temp = update_time(full);
170
-
171
- if (temp > max) {
172
-
173
- max = temp;
174
-
175
- strcpy(latest, dp->d_name);
176
-
177
- }
178
-
179
- }
180
-
181
-
182
-
183
- closedir(dir);
184
-
185
- return max;
186
-
187
- }
188
-
189
- ```
190
-
191
- stat構造体のst_mtimeメンバには、最終更新日時を表す数値が入っています。
192
-
193
- この数値は、1970年1月1日午前0時0分0秒からの経過秒数(UNIX時間)を表すので、大きな数値ほど最新のファイルということになります。
194
-
195
- すべてのファイルのUNIX時間を調べることで、最新のファイルを知ることができます。