WIN32_FIND_DATA - 获取绝对路径

时间:2012-09-11 00:19:14

标签: c++ windows filesystems directory absolute-path

我正在使用这样的东西:

std::string tempDirectory = "./test/*";

WIN32_FIND_DATA directoryHandle;
memset(&directoryHandle, 0, sizeof(WIN32_FIND_DATA));//perhaps redundant???

std::wstring wideString = std::wstring(tempDirectory.begin(), tempDirectory.end());
LPCWSTR directoryPath = wideString.c_str();

//iterate over all files
HANDLE handle = FindFirstFile(directoryPath, &directoryHandle);
while(INVALID_HANDLE_VALUE != handle)
{
    //skip non-files
    if (!(directoryHandle.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
    {
        //convert from WCHAR to std::string
        size_t size = wcslen(directoryHandle.cFileName);
        char * buffer = new char [2 * size + 2];
        wcstombs(buffer, directoryHandle.cFileName, 2 * size + 2);
        std::string file(buffer);
        delete [] buffer;

        std::cout << file;
    }

    if(FALSE == FindNextFile(handle, &directoryHandle)) break;
}

//close the handle
FindClose(handle);

打印相对目录./test/*中每个文件的名称。

有没有办法确定这个目录的绝对路径,就像realpath()在Linux上没有涉及像BOOST这样的第三方库一样?我想打印每个文件的绝对路径。

2 个答案:

答案 0 :(得分:10)

请参阅GetFullPathName功能。

答案 1 :(得分:4)

您可以尝试GetFullPathName

或者您可以使用SetCurrentDirectoryGetCurrentDirectory。您可能希望在执行此操作之前保存当前目录,以便之后可以返回它。

在这两种情况下,您只需要获取搜索目录的完整路径。 API调用很慢。在循环内部,您只需组合字符串。

相关问题