c - Glob 与用户提供的目录?

标签 c glob

我正在编写一个程序,该程序应该搜索用户提供的目录,以便找到该目录中在给定时间的一天内被访问、修改或更改的所有文件。我有两个明确的问题,也许还有另一个。

第一个问题是我只能让程序进行浅搜索,它不会遍历任何子目录。我确信它与我连接到目录缓冲区的内容有关(现在是 .)。第二个问题是它没有搜索每个文件,尽管它确实查看了其中的大部分 - 我认为这可以追溯到问题一。第三个“问题”是当我检查每个文件的访问时间时,它们似乎都是一样的(尽管我没有更改/修改时间的问题)。如果这可能会影响访问时间,我正在通过 VM 在 Ubuntu 上运行。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <glob.h>

/* Function that checks if specified file was accessed, modified, or
changed within a day of the specified time.                 */
void checkFile(long long time, char * fileName) {
struct stat *s;
time_t accessTime;
time_t modTime;
time_t changeTime;
s = malloc(sizeof(struct stat));
if(stat(fileName,s) == 0) {
    accessTime = s->st_atime;
    modTime = s->st_mtime;      
    changeTime = s->st_ctime;
    if((time - accessTime) <= 86400 && (time - accessTime) >= -86400)
        printf("%s\n",fileName);
    else if((time - modTime) <= 86400 && (time - modTime) >= -86400)
        printf("%s\n",fileName);
    else if((time - changeTime) <= 86400 && (time - changeTime) >= -86400)
        printf("%s\n",fileName);
}
free(s);
}

void searchDirectory(long long time, glob_t globbuf) {
if(globbuf.gl_pathc == 0)
    printf("there were no matching files");
else {
    int i;
    for(i = 0; i < globbuf.gl_pathc; i++)
        checkFile(time,globbuf.gl_pathv[i]);
}
}

int main(int argc, char** argv) {
    long long time = atol(argv[1]);
    char * buf = argv[2];
    strcat(buf,"*.*");
    glob_t globbuf;
    glob(buf, 0, NULL, &globbuf);
    searchDirectory(time,globbuf);
    globfree(&globbuf);
    return 0;
}

感谢您的宝贵时间!

最佳答案

你不应该

cat(buf, "*.*");

...因为“buf”是指向操作系统提供的字符串的指针 - 您不知道该缓冲区是否足够大以容纳您添加的额外文本。您可以分配一个大缓冲区,将 argv[2] 的内容复制到其中,然后附加 "*.*",但为了真正安全,您应该确定长度argv[2] 并确保您的缓冲区足够大。

可以使用struct stat结构的st_mode成员判断文件是否为目录(检查是否等于S_IFDIR) .如果是,您可以将其设为当前目录,并按照 jonsca 的建议,再次调用您的 searchDirectory 函数。但是在使用递归时,您通常希望确保对递归的深度有限制,否则您可能会溢出堆栈。这是一种“深度优先搜索”。我更喜欢的解决方案是使用队列进行“广度优先搜索”:基本上将第一个 glob 推到列表的开头,然后重复从该列表中取出第一项并搜索它,将新目录添加到列表的末尾边走边列出,直到列表为空。

在评估这样的项目时,老师们喜欢给那些不太容易搞砸的项目加分 :)

附言我猜访问时间问题是 VM/文件系统/等不兼容,而不是你的错。

关于c - Glob 与用户提供的目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5906409/

相关文章:

python - 使用 QCompleter 全局输入?

python - 当从列表中获取 Python Glob 模块的参数时,文件名大小写更改为小写

npm - 如果它在 'npm shell' 中有效,为什么不能在 npm package.json 脚本中使用(用于递归 globbing)?

Perl Globbing a Variable 在第一场比赛中停止

c - 查找数组中未出现两次的整数

c - 查找某个文件的所有硬链接(hard link)

C中的通用数据结构库

c - 在 Windows 操作系统中使用 C 运行 GTK 库的任何方式?

c++ - 如何将 AS3 ByteArray 转换为 wchar_t const* 文件名? (土坯炼金术)

powershell - 使用动态构造的排除模式数组,使用 Get-ChildItem -Exclude 过滤子文件夹