扫描目录以查找 c 中的文件 [英] scan a directory to find files in c

查看:21
本文介绍了扫描目录以查找 c 中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 c 中创建一个函数,它会扫描我所有的路径 C: emp (Windows) 以搜索我通过的文件(例如 test.txt),并且每次找到时都会返回步骤的路径在这个文件的底部写一些东西的另一个函数.我设法执行写入文件的功能,但无法弄清楚如何扫描文件夹并传递找到的文件的地址.

I'm trying to create a function in c which scans all my path C: temp (Windows) to search for a file that I pass (eg test.txt) and each time it finds one return the path to steps another function to write something in the bottom of this file. I managed to do the function that writes to the file but can not figure out how to do that scans the folder and pass the address of the file found.

推荐答案

#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
", 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/
",depth,"",entry->d_name);
            /* Recurse at a new indent level */
            printdir(entry->d_name,depth+4);
        }
        else printf("%*s%s
",depth,"",entry->d_name);
    }
    chdir("..");
    closedir(dp);
}

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

这篇关于扫描目录以查找 c 中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆