c++ - 获取目录列表

标签 c++ pointers vector filesystems

我有一个 vector 问题,我已经尝试解决了很长一段时间。我会立即发布代码并进行解释。

#include "filesystem.h"
#include <vector>
using namespace Filesystem;

wchar_t** Path::ListDir()
{
    /*struct dirEntry
    {
        wchar_t entry[MAX_PATH];
    };*/
    vector<wchar_t*> pathList = vector<wchar_t*>();
    WIN32_FIND_DATA findData;
    HANDLE dirHandle = new HANDLE;
    wchar_t* path = L"C:\\*";

    dirHandle = FindFirstFile(path, &findData);
    if (dirHandle == INVALID_HANDLE_VALUE)
        return NULL;

    while (FindNextFile(dirHandle, &findData) != 0)
    {
        pathList.push_back(findData.cFileName);
    }

    FindClose(dirHandle);

    return NULL;
}

这是我正在编写的文件系统类的一部分。它应该列出目录中的所有文件并将它们作为二维字符串数组返回。如果我这样做,它会用最后一个文件乘以文件夹中的文件数来填充列表。这不是我想要它做的。我认为这可能是因为我传递了一个指向 push_back 的指针,但我还没有找到修复它的方法。我在 Windows 上编码,顺便说一句。

如果这里有人知道如何做到这一点,那就太好了。

最佳答案

您正在存储 findData.cFileName 的地址在vector N次。

你需要复制这个。可能使用:

vector<std::wstring> pathList;

编辑:其他小点:

vector<wchar_t*> pathList = vector<wchar_t*>();
HANDLE dirHandle = new HANDLE;

可以替换为:

vector<wchar_t*> pathList;
HANDLE dirHandle;

如果您必须返回wchar_t**然后(例如):

// '+1' for NULL terminating string as the callers needs
// know where the array ends.
wchar_t** result = new wchar_t*[pathList.size() + 1];
*(result + pathList.size()) = 0;

for (size_t i = 0; i < pathList.size(); i++)
{
    wchar_t* name = new wchar_t[pathList[i].length() + 1];
    std::copy(pathList[i].begin(), pathList[i].end(), name);
    *(name + pathList[i].length()) = L'\0';
    *(result + i) = name;
}

return result;

来电者必须记住delete[]返回数组:

Path p;
wchar_t** list = p.ListDir();
...
for (size_t i = 0; 0 != *(list + i); i++)
{
    delete[] *(list + i);
}
delete[] list;

尽管这是 C++,但您应该使用 std::vector<std::wstring> .

关于c++ - 获取目录列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8745384/

相关文章:

c++ - 如何在纹理映射过程后合并两个 .obj 文件?

c++ - 可用于打印方法名称的宏/关键字?

c - n 个大小的 C 数组的第 n 个索引是否包含它的大小?

c++ - vector 元素输出垃圾

C++ 模板集合类型

c++ - vector<char> 优于字符串的好处?

c++ - 顶点着色器的定点算法

c++ - 两个指针之间的转换/转换

c - 将预分配的 char* 缓冲区传递给 c 函数

c - 函数中的指针语法