首页 > 解决方案 > 如何在没有dirent.h或boost的特定目录中查找文件列表

问题描述

我需要制作这个可以从学校项目目录中找到文件名的标题,尽管重要的是要提到我的老师非常严格,我不允许使用已经制作的库(dirent.h,boost等)。简单地说,我必须从头开始。

我实际上被允许使用的唯一 2 个功能是

// They more test accesibility rather than actual existance but it is enough

// LPCSTR = constant long pointer to string
// similar to:  char* pathToFile 

bool DoesFileExist(LPCSTR pathToFile)  
{
    std::ifstream file(pathToFile);
    return file.good();
}

bool DoesDirExist(LPCSTR pathToDir)
{
     DWORD dwAttrib = GetFileAttributes(pathToDir);
     return (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}

如果我只需要打印名称,我认为递归函数效果最好。这就是代码的行为方式。

void PrintSubfiles(LPCSTR CurrentDirectory)
{
    CHAR pathToSomething[MAX_PATH];
    // this is where the string takes the path of either a file or a directory
    // I imagined the principle of the GetNextPath() function similar to strtok()
    GetNextPath(CurrentDirectory,pathToSomething); 

    while (pathToSomething != NULL)
    {
        if (DoesDirExist(pathToSomething))
        {
             // print the name of this directory and enter it
             std::cout<<"IN DIRECTORY: "<<pathToSomething<<std::endl;
             PrintSubFiles(pathToSomething);   
        }

        if (DoesFileExist(pathToSomething))
        {
             // print the file name
             std::cout<<"FILE: "<<pathToSomething<<std::endl;
        }

        GetNextPath(NULL,pathToSomething);
    }
}

我实际上不知道如何实现该GetNextPath()功能。它不需要超快或内存高效。我只需要将数据获取到该pathToSomething字符串。知道如何在没有这些库的情况下做到这一点吗?

编辑:此标头专门用于 Windows。无需便携式解决方案。

标签: c++file

解决方案


推荐阅读