首页 > 解决方案 > 打印当前目录中名称以0-9开头的最近修改的文件/目录的名称

问题描述

我需要编写一个简单的程序来打印当前目录中最近修改的文件的名称,该文件的名称以 0-9 开头。到目前为止,我可以让它打印以 0-9 开头的文件的名称,但它无法始终打印最近修改的文件。我一直被困在这部分,我非常迫切需要弄清楚这一点。任何帮助或提示都会有很大帮助!谢谢!

下面是我的代码:

#include <dirent.h>  
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <sys/types.h>  
#include <sys/stat.h>  
#include <time.h>  
#include <unistd.h>  

int main(void){ 
    // Open the current directory  
    DIR* currDir = opendir("./");  
    struct dirent *aDir;  
    time_t lastModifTime;  
    struct stat dirStat;  
    int first_file_checked = 0;  
    char directoryName[256];  

    // Go through all the entries  
    while((aDir = readdir(currDir)) != NULL){  
        // only check on directories with a name that starts with 0-9  
        if (48 <= (int)aDir->d_name[0] && (int)aDir->d_name[0] <= 57) {  
            // Get meta-data for the current entry  
            stat(aDir->d_name, &dirStat);    
            // Use the difftime function to get the time difference between the current value of lastModifTime and the st_mtime value of the directory entry  
            if(first_file_checked == 0 || difftime(dirStat.st_mtime, lastModifTime) > 0){  
                lastModifTime = dirStat.st_mtime;  
                memset(directoryName, '\0', sizeof(directoryName));  
                strcpy(directoryName, aDir->d_name);  
            }  
            first_file_checked = 1;  
        }  
    }  
    // Close the directory  
    closedir(currDir);  
    printf("The last file/directory modified in the current directory is %s\n", directoryName);  
    return 0;  
}  

标签: c

解决方案


在这里工作:

顺便说一句:你不检查目录,你需要添加一个检查d_type来完成它。


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>

int main(void){
    // Open the current directory  
    DIR* currDir ;
    struct dirent *aDir;
    time_t lastModifTime;
    struct stat dirStat;
    int count ;
    char thename[256] = "";

    // Go through all the entries  
    currDir = opendir("./");
    for(count=0; (aDir = readdir(currDir)) ; ){
        int rc;
        // only check on directories with a name that starts with 0-9  
        if (aDir->d_name[0] < '0' || aDir->d_name[0] > '9' ) continue;
            // Get meta-data for the current entry  
        rc = stat(aDir->d_name, &dirStat);
        if (rc < 0) continue; // check the return value!

        if(!count++ || dirStat.st_mtime < lastModifTime ){
            lastModifTime = dirStat.st_mtime;
            strcpy(thename, aDir->d_name);
        }
    }
    // Close the directory  
    closedir(currDir);
    if (count) {
        printf("%d files checked. The last file/directory modified in the current directory is %s(time=%u)\n"
                , count, thename, (unsigned) lastModifTime);
        }
    else {
        printf("No files/directories were found\n");
        }
    return 0;
}

推荐阅读