扫描一个目录以查找C语言中的文件

7
我正在尝试创建一个C语言函数,扫描我所有的路径C:\temp(Windows),以查找我传递的文件(例如test.txt),每次找到一个文件时返回该文件的路径,然后将其传递给另一个函数,在该文件的底部写入一些内容。我已经成功实现了写入文件的函数,但是不知道如何扫描文件夹并传递找到的文件地址。

如果您还想检查文件扩展名,则 scandir() 可能会有用。https://stackoverflow.com/questions/22886290/c-get-all-files-with-certain-extension - Sergey Ponomarev
2个回答

14
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
void printdir(char *dir, int depth)
{
    DIR *dp;
    struct dirent *entry;
    struct stat statbuf;
    if((dp = opendir(dir)) == NULL) {
        fprintf(stderr,"cannot open directory: %s\n", dir);
        return;
    }
    chdir(dir);
    while((entry = readdir(dp)) != NULL) {
        lstat(entry->d_name,&statbuf);
        if(S_ISDIR(statbuf.st_mode)) {
            /* Found a directory, but ignore . and .. */
            if(strcmp(".",entry->d_name) == 0 ||
                strcmp("..",entry->d_name) == 0)
                continue;
            printf("%*s%s/\n",depth,"",entry->d_name);
            /* Recurse at a new indent level */
            printdir(entry->d_name,depth+4);
        }
        else printf("%*s%s\n",depth,"",entry->d_name);
    }
    chdir("..");
    closedir(dp);
}

int main()
{
    printf("Directory scan of /home:\n");
    printdir("/home",0);
    printf("done.\n");
    exit(0);
}

但是我应该在哪里插入我的窗口扫描路径,比如“c:\tools”,然后是我想要查找和修改的txt文件,比如“test.txt”,然后是我想要插入到其末尾的字符串,比如“Sometext”? - AleMal
1
将目录名传递给函数printdir(“c:/ xxx / xx /”,0); 根据您的需要修改代码,此代码将列出给定目录下的所有项目。 - Akhil Thayyil
我已经修改了代码,用于在目录LOG中查找名为Filter.txt的文件,并在文件末尾写入“done”...但是不起作用。int main(){ printf("扫描/home目录:\n"); printdir("C:/LOG/Filter.txt",0); printf("完成。\n"); exit(0);} - AleMal
int main() { printf("扫描/home目录:\n"); printdir("C:/LOG/Filter.txt",0); printf("完成。\n"); exit(0); } - Akhil Thayyil
1
请注意,虽然 chdir(dir); 可以工作,但是最后的 chdir(".."); 不是“返回到您所在的目录”的通用解决方案。我认为它只适用于命名目录是当前目录的直接子目录的情况。在 POSIX 系统上,可以使用 fchdir() 安全地更改目录:在进行初始的 chdir() 之前,int cwd = open(".", O_RDONLY); 打开当前目录,然后 fchdir(cwd) 返回到该目录,然后当然要跟随 close(cwd) - Jonathan Leffler

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接