【问题标题】:WIN32_FIND_DATA returns "." and ".." when listing files in a DirectoryWIN32_FIND_DATA 返回“。”和“..”在目录中列出文件时
【发布时间】:2017-05-15 11:50:02
【问题描述】:

我正在编写一个可以在 Windows 和 Linux 上运行的虚拟文件系统。这是一项任务,因此不允许使用诸如 Boost 之类的外部事物。对于 Windows 版本,我正在尝试编写一个将所有文件挂载到给定目录中的函数。这是说的功能:

void FileSystem::MountDirectory(const std::string directory)
{
    WIN32_FIND_DATA search_data;

    memset(&search_data, 0, sizeof(WIN32_FIND_DATA));

    std::wstring wDir = StringToWstring(directory);
    LPCWSTR dir = wDir.c_str();
    HANDLE handle = FindFirstFile(dir, &search_data);

    if (handle == INVALID_HANDLE_VALUE)
    {
        std::cout << "ERROR: Unable to mount files in path: " << directory << std::endl;
    }
    else
    {
        while (handle != INVALID_HANDLE_VALUE)
        {
            std::string fileName = WCHARArrayToString(search_data.cFileName);
            File file(fileName, directory);
            m_MountedFiles.push_back(file);
            std::cout << "Succesfully mounted the file: " << fileName << std::endl;
            if (FindNextFile(handle, &search_data) == FALSE)
            {
                std::cout << "No more files to mount." << std::endl;
                break;
            }
        }
    }
    FindClose(handle);
}

我做了一些内联函数来帮助从 std::string 到 std::wstring 的转换,反之亦然。我在 main.cpp 中创建了一个 FileSystem 对象,并在我的 D: 驱动器上的 TestFolder 的路径上调用 MountDirectory:

"D:\TestFolder\*.*"

到目前为止,此代码有效,但在我的测试文件夹的输出中,它总是在其余文件之前先打印:

成功挂载文件:.

成功挂载文件:..

为什么这些“文件”会被 WIN32_FIND_DATA 拾取,我该如何防止?

【问题讨论】:

  • 你应该添加winapi标签。
  • 我不记得有什么方法可以阻止它,但是您可以通过简单的比较来忽略它们。
  • @TigerHwang 是的,我认为这是一个解决方案。只是真的想知道为什么会发生这种情况,因为简单的比较过滤器似乎是一个肮脏(但有效)的解决方案。
  • 点(当前目录)和点点(父)目录在 Linux 和 Windows 中都是标准目录名称,例如参见here
  • @Tom 啊,我明白了。这就说得通了。感谢您的回复。

标签: c++ windows file winapi unicode


【解决方案1】:

它们分别代表当前目录和父目录。如果您要枚举所有文件和目录,那么您将无法禁止枚举这些对象。如果您不想打印它们,请让您的代码检测它们并忽略它们。

【讨论】:

    猜你喜欢
    • 2013-05-30
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 2012-04-07
    • 2012-11-14
    相关资源
    最近更新 更多