实现功能:打开某目录,查找该目录下文件的修改时间最老的那个文件;
C(string.h)字符串操作函数总结:https://blog.csdn.net/qq_33757398/article/details/81212618
代码如下:
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
int main(int argc, char *argv[])
{
DIR *pDir = NULL;
struct dirent * pEnt = NULL;
unsigned int cnt = 0;
pDir = opendir(argv[1]);
if (NULL == pDir) {
perror("opendir");
return -1;
}
time_t timep;
struct tm *p;
time(&timep);
printf("time():%d\n", (int)timep);
p = localtime(&timep);
printf("%4d-%2d-%2d %2d-%2d-%2d\n", p->tm_year + 1900, p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec);
time_t oldestTime = timep;
struct stat sb;
char oldestFile[128] = {0};
while (1) {
pEnt = readdir(pDir);
if(pEnt != NULL) {
if (pEnt->d_type == DT_REG) {
// printf("是普通文件:");
} else if ((strcmp(pEnt->d_name, ".") == 0) || (strcmp(pEnt->d_name, "..") == 0)) {
printf("不是普通文件: name is [%s]\n", pEnt->d_name);
continue;
}
// printf("name:[%s] \n", pEnt->d_name);
cnt++;
} else {
break;
}
char filePath[128] = {0};
sprintf(filePath, "%s%s", argv[1], pEnt->d_name);
// printf("filePath: %s\n", filePath);
if (stat(filePath, &sb) == -1) {
perror("stat");
exit(EXIT_SUCCESS);
}
if (oldestTime > sb.st_mtime) {
oldestTime = sb.st_mtime;
printf("Last file modification: %s", ctime(&sb.st_mtime));
printf("filePath: %s\n", filePath);
memcpy(oldestFile, filePath, strlen(filePath));
}
// printf("Last file modification: %s", ctime(&sb.st_mtime));
printf("\nLast file modification: %d, oldestTime: %d\n", sb.st_mtime, oldestTime);
};
printf("all file count:%d\n", cnt);
printf("oldestFile is: %s\n", oldestFile);
return 0;
}