列出指定目录下在过去一小时内被修改的文件

来源:互联网 发布:单目标粒子群算法代码 编辑:程序博客网 时间:2024/05/29 17:33

要求: 输出该路径下所有当前时刻起前一小时内被修改的文件及其对应的最后被修改时间。

知识点:

使用time函数获得当前的时间:time_t time(time_t *t)

#include<time.h>

此函数会返回从公元1970年1月1日的UTC时间从0时0分0秒算起到现在所经过的秒数。如果t 并非空指针的话,此函数也会将返回值存到t指针所指的内存。

代码:

#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<unistd.h>
#include<errno.h>
#include<dirent.h>
#include<sys/types.h>
#include<time.h>
#define SIZE 1024
int dir_run(char *path)
{      

    time_t timer;
    struct tm * tblock;
    timer= time(NULL);
    tblock=localtime(&timer)
;//获取当前时间
    DIR *dir;  
    dir = opendir(path);   
    if (dir == NULL)
    {       
        return -1;  
    }
    struct stat st;
    struct dirent *entry;
    char fullpath[SIZE];
    while((entry = readdir(dir)) != NULL)
    {      
        if((strcmp(entry->d_name, ".") == 0) || (strcmp(entry->d_name, "..") == 0))
        {        
            continue;   
        }
        sprintf(fullpath, "%s/%s", path, entry->d_name);     
        if(lstat(fullpath, &st) != 0)
        {          
            continue;
        }
        if(S_ISDIR(st.st_mode))
        {      
            printf("%s目录下过去一个小时内被修改的文件:\n",entry->d_name);
            dir_run(fullpath);  
            printf("\n");
        }
        else
        {
                        int nowtime = time((time_t*)NULL);
                        if((nowtime-(st.st_mtime))<=3600)
                        {
                            printf("%s\n",entry->d_name);
                            printf("当前时间:%s\n",asctime(tblock));
                            printf("%s最后被修改的时间%s\n",entry->d_name,ctime(&st.st_mtime));
                        }
        }
    }   
    closedir(dir);
    return 0;
}
int main(int argc,char*argv[])
{
    if(argc!=2)
    {
        printf("参数不正确!正确格式:./main filepath\n");
        exit(1);
    }
    dir_run(argv[1]);
    return 0 ;
}

0 0
原创粉丝点击