遍历某目录找到文件修改时间最老的文件

实现功能:打开某目录,查找该目录下文件的修改时间最老的那个文件;

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

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值