C语言实现遍历查找某目录下时间最老的文件

功能需求:

        需要查找某个目录下创建时间最早的目录或文件

代码实现:

#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;
}

测试效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙猫不是猫!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值