C++获取文件目录及时间的示例代码

示例代码

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using std::vector;
using std::string;
int main(int argc, char *argv[])
{
	struct stat dirstat;
    int result;
	DIR *d;
	struct dirent *de;
	vector<string>dirVec;
	struct timespec tstmtime;

	if (argc < 2)
	{
		printf("param-num:%d \r\n", argc);
		return -1;
	}
	
	d = opendir(argv[1]);
	if (d == NULL)
    {
		printf("opendir: %s failed ! \r\n", argv[1]);
		return -1;
	}
		while((de = readdir(d)) != NULL)
	{
		string str(de->d_name);
		dirVec.push_back(str);
	}
	
	for(auto& dir : dirVec)
	{
		lstat(dir.c_str(), &dirstat);
		if ((dirstat.st_mode & S_IFMT) == S_IFDIR)	//目录文件
		{
			printf("dir:%s, at-time:%ld, mt-time:%ld, ct-time:%ld \r\n", 
					dir.c_str(), dirstat.st_atime, dirstat.st_mtime, dirstat.st_ctime);
			
			if (strcmp(dir.c_str() , ".")==0 || strcmp(dir.c_str() , "..")==0)
			{
				printf("Don't touch current dir:%s \r\n", dir.c_str());
				continue;
			}
			
			clock_gettime(CLOCK_REALTIME, &tstmtime);
			time_t ttSec = tstmtime.tv_sec;
			printf("Current time:%ld \r\n", ttSec);
			if (ttSec > dirstat.st_ctime + 300)
			{
				printf("dir:%s, created over 100 \r\n", dir.c_str());
				
			}
			
		}
	}
	
	closedir(d);
}

编译&运行结果

kongcb@tcu-pc:~/testcode$ g++ testdir.cpp -o testdir -std=c++11
kongcb@tcu-pc:~/testcode$ ./testdir ./
dir:lesson-2, at-time:1662426945, mt-time:1662426945, ct-time:1662426945 
Current time:1662513263 
dir:lesson-2, created over 100 
dir:., at-time:1662513260, mt-time:1662513254, ct-time:1662513254 
Don't touch current dir:. 
dir:.., at-time:1662431148, mt-time:1662102681, ct-time:1662102681 
Don't touch current dir:.. 
dir:test3, at-time:1662426184, mt-time:1662348973, ct-time:1662348973 
Current time:1662513263 
dir:test3, created over 100 
dir:test-2, at-time:1662426184, mt-time:1662346841, ct-time:1662346841 
Current time:1662513263 
dir:test-2, created over 100 
dir:gcc-12.2.0, at-time:1662434999, mt-time:1660898031, ct-time:1662434987 
Current time:1662513263 
dir:gcc-12.2.0, created over 100 
dir:test-1, at-time:1662426184, mt-time:1662346839, ct-time:1662346839 
Current time:1662513263 
dir:test-1, created over 100 
kongcb@tcu-pc:~/testcode$ 

解析

有几点注意:
1:函数readdir打开文件夹
2:函数lstat查看文件属性
3:函数clock_gettime获取系统时间,用于时间先后对比

你可能感兴趣的:(C/C++编程,c++,开发语言,c语言)