如何使用C 打开目录

How to open a Directory with C++

本文关键字:何使用      更新时间:2023-10-16

我是C 的新手,对于我的第一个任务,我被要求打开一个目录(及其所有子目录(,而仅存储.txt文件路径。这就是我到目前为止所做的,但是我遇到了多个错误。谁能帮忙?

#include<stdio.h>
#include<sys/stat.h>
#include<iostream>
#include<string.h>
#include<string>
#include<dirent.h>
using namespace std;
void explore(char *dir_name){
    DIR *dir; // pointer to directory
    struct dirent *entry; // all stuff in the directory
    struct stat info; // info about each entry
    dir = opendir(dir_name);
    if (!dir)
    {
        cout << "Directory not found" << endl;
        return;
    }
    while ((entry = readdir(dir)) != NULL)
    {
        if (entry->d_name[0] != '.')
        {
            string path = string(dir_name) + "/" + string(entry->d_name);
            cout << "Entry = " << path << endl;
            stat(path,&info) //
            if (S_ISDIR(info.st_mode))
            {
                explore(path);
            }
        }
    }
    closedir(dir);
}
int main{
    explore(".");
    return 0;
}

您在Linux上吗?你为什么让事情复杂化?有一种叫做"文件树步行"的东西,可以用最小的努力来完成您想要的事情。这是一个快速示例。有关输入参数的更多信息,请执行man ftw

#include <iostream>
#include <ftw.h>
#include <fnmatch.h>
static int explore( const char *fpath,
                    const struct stat *sb,
                    int typeflag )
{
    if (typeflag == FTW_F)  ///< it's a file
    {
        if (fnmatch("*.txt", fpath, FNM_CASEFOLD) == 0) ///< it's a .txt file
        {
            std::cout << "found txt file: " << fpath << std::endl;
        }
    }
    return 0;
}
int main()
{
    ftw(".", explore, 8);
    return 0;
}