gpt4 book ai didi

c - 使用标准 C 库或 POSIX 库扫描 UNIX 目录中的文件

转载 作者:行者123 更新时间:2023-11-30 15:45:34 40 4
gpt4 key购买 nike

C 程序是否可以查看某个目录中的文件并与它们交互?例如,假设我通过 system() 函数使用 wget 下载了一个文件,并且我想查看该文件的名称是什么。有什么方法可以让我仅通过标准 C 库或 POSIX 库来完成此任务吗?

最佳答案

这会查找目录中不到 5 秒前修改的文件 - 没有错误检查。

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

void dirchk(const char *arg) // arg=name of directory
{
time_t when = time(NULL) -5; // 5 secs ago
struct stat st;
DIR *dirp=opendir(arg);
struct dirent *d=readdir(dirp);
while (d != NULL)
{
if ((d = readdir(dirp)) != NULL)
{
stat(d->d_name, &st);
if( when - st.st_mtime <=5 )
printf("%s\n", d->d_name);
}
}
closedir(dirp);
return;
}

int main()
{
dirchk(".");
return 0;
}

“。”是当前工作目录。

关于c - 使用标准 C 库或 POSIX 库扫描 UNIX 目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18938860/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com