2012-09-11 190 views
6

我使用的是这样的:WIN32_FIND_DATA - 获取绝对路径

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一样?我想打印每个文件的绝对路径。

+0

您是否要求[UNC](http://en.wikipedia.org/wiki/Uniform_Naming_Convention#Uniform_Naming_Convention)路径? –

+0

我不认为我需要这样一个通用的解决方案。本地路径现在应该做得很好(如C:\ bla \ blabla \ etc)。 –

+0

不保证有本地路径。 –

回答

9

请参阅GetFullPathName函数。

+4

具体而言,在目录上调用'GetFullPathName',并将其与'WIN32_FIND_DATA'中的文件名组合起来。 –

+0

@RaymondChen,这是怎么完成的?在我的情况(类似于问题),我有一个通配符作为字符串的路径,但我只有处理找到的文件。由于该路径可能包含通配符,因此目录可能不存在,因此我需要获取找到的文件的父目录,然后获取该目录的完整路径? –

+1

@JavierMr如果您有新问题,请发布新问题。我不知道你的意思是“目录可能不存在”。目录就在那里:在'./test/*'中,目录是'。/ test'。目录部分不允许使用通配符,因此获取目录不需要您处理通配符。 –

4

您可以尝试GetFullPathName

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

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