c - 打印当前目录中名称以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;
}
解决方案
在这里工作:
顺便说一句:你不检查目录,你需要添加一个检查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;
}
推荐阅读
- javascript - 使用jquery动画角度5动画方式(平滑滚动)
- spring - 当我使用 @Requestbody 时,我从带有 @Data 的实体中得到了 null
- java - 类型转换和泛型类型
- c++ - 了解复制构造函数和引用
- python - Python Regex Bullet Point 和多行匹配
- hl7-fhir - HL7 FHIR 将资源标记为匿名
- .htaccess - 301 将 HTTP 重定向到 HTTPS - 非 www 到 www
- javascript - 反应儿童抛出 PropTypes 错误
- r - 在同一图中绘制 ecdf 和密度并放大到特定部分
- c# - ASP.NET Core 2.0 中的验证:语法与验证问题