C++ WIN32_查找_数据-获取绝对路径

C++ WIN32_查找_数据-获取绝对路径,c++,windows,filesystems,directory,absolute-path,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());

我用的是这样的东西:

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);
std::string tempDirectory=“./test/*”;
WIN32_FIND_DATA directoryHandle;
memset(&directoryHandle,0,sizeof(WIN32_FIND_DATA))//也许是多余的???
std::wstring-wideString=std::wstring(tempDirectory.begin(),tempDirectory.end());
LPCWSTR directoryPath=wideString.c_str();
//迭代所有文件
HANDLE HANDLE=FindFirstFile(directoryPath和directoryHandle);
while(无效的句柄值!=句柄)
{
//跳过非文件
if(!(directoryHandle.dwFileAttributes和文件属性目录))
{
//从WCHAR转换为std::string
size\u t size=wcslen(directoryHandle.cFileName);
char*buffer=新字符[2*size+2];
wcstombs(缓冲区,directoryHandle.cFileName,2*size+2);
字符串文件(缓冲区);
删除[]缓冲区;
std::cout查看函数。

您可以尝试

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


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

您需要路径吗?我认为我不需要这样一个通用的解决方案。本地路径现在应该很好(如C:\bla\blabla\etc).同意,但在我的情况下,应用程序将始终从本地驱动器运行。因此,在这种特殊情况下,我要问的是,是否有一个API函数可以返回可用的绝对路径?
std::vector
只是一个动态分配的
char
数组,因此如果您
.resize()
将其设置为所需大小,可以调用
.data()
获取指向其初始元素的指针。对于
wcstombs
,该指针与
new
使用数组生成的指针没有区别。提示:可以使用
WIN32\u FIND\u data directoryHandle={0}消除memset在C和C++中都有效。具体地,在目录上调用<代码> GETFultPosith</C>,并将它与<代码> Win 32中的文件名结合起来。@ RaymondChen,这是怎么做的?在我的例子中(类似于问题)我有一个以通配符作为字符串的路径,但我只有找到的文件的句柄。由于路径可能包含通配符,目录可能不存在,因此我需要获取找到的文件的父目录,然后获取该目录的完整路径?@JavierMr如果你有新问题,请发布新问题。我不知道你的意思是什么n通过“目录可能不存在”。目录就在那里:在
/test/*
中,目录是
/test
。目录部分不允许使用通配符,因此获取目录不需要处理通配符。@RaymondChen,实际上完成问题中的代码以打印绝对路径就足够了。我不知道通配符是什么如果只允许在路径的目录部分,那么肯定会使事情变得更容易