簡體   English   中英

獲取.exe目錄中列出的所有文件,不知道位置

[英]Get all files listed inside .exe directory not knowing location

我想我的問題是這樣的 - 如何將exe位置的目錄作為LPCWSTR獲取,以便我可以將其輸入到我的代碼中

#include <iostream>
#include <Windows.h>
int main(int argc, char **argv)
{
WIN32_FIND_DATA a;
HANDLE swap = FindFirstFile(/*(LPCWSTR)__exe_directory__*/,&a);
if (swap!=INVALID_HANDLE_VALUE)
{
    do
    {
        char *sptn = new char [lstrlen(a.cFileName)+1];
        for (int c=0;c<lstrlen(a.cFileName);c++)
        {
            sptn[c]=char(a.cFileName[c]);
        }
        sptn[lstrlen(a.cFileName)]='\0';
        std::cout<<sptn<<std::endl;
    }
    while (FindNextFile(swap,&a));
}
else std::cout<<"undetected file\n";
FindClose(swap);
system("pause");
}

它會返回目錄中列出的文件而不會出錯。 我知道我的代碼已經在給定目錄的情況下工作,我已經測試了它。

關鍵是使用GetModuleFileName() (傳遞nullptr作為模塊句柄,引用當前進程EXE),然后調用PathRemoveFileSpec() (或PathCchRemoveFileSpec() ,如果你不關心Windows 8之前的Windows版本)從路徑中刪除文件規范。

要使用PathRemoveFileSpec()您必須與Shlwapi.lib鏈接,如MSDN文檔中所述

請參閱此可編譯代碼作為示例:

#include <iostream>     // For console output
#include <exception>    // For std::exception
#include <stdexcept>    // For std::runtime_error
#include <string>       // For std::wstring
#include <Windows.h>    // For Win32 SDK
#include <Shlwapi.h>    // For PathRemoveFileSpec()

#pragma comment(lib, "Shlwapi.lib")

// Represents an error in a call to a Win32 API.
class win32_error : public std::runtime_error 
{
public:
    win32_error(const char * msg, DWORD error) 
        : std::runtime_error(msg)
        , _error(error)
    { }

    DWORD error() const 
    {
        return _error;
    }

private:
    DWORD _error;
};

// Returns the path without the filename for current process EXE.
std::wstring GetPathOfExe() 
{
    // Get filename with full path for current process EXE
    wchar_t filename[MAX_PATH];
    DWORD result = ::GetModuleFileName(
        nullptr,    // retrieve path of current process .EXE
        filename,
        _countof(filename)
    );
    if (result == 0) 
    {
        // Error
        const DWORD error = ::GetLastError();
        throw win32_error("Error in getting module filename.", 
                          error);
    }

    // Remove the file spec from the full path
    ::PathRemoveFileSpec(filename);

    return filename;
}

int main() 
{
    try 
    {
        std::wcout << "Path for current EXE:\n"
                   << GetPathOfExe() 
                   << std::endl;
    } 
    catch (const win32_error & e) 
    {
        std::cerr << "\n*** ERROR: " << e.what()
                  << " (error code: " << e.error() << ")" 
                  << std::endl;
    } 
    catch (const std::exception& e) 
    {
        std::cerr << "\n*** ERROR: " << e.what() << std::endl;
    }
}

在控制台中:

 C:\\Temp\\CppTests>cl /EHsc /W4 /nologo /DUNICODE /D_UNICODE get_exe_path.cpp get_exe_path.cpp C:\\Temp\\CppTests>get_exe_path.exe Path for current EXE: C:\\Temp\\CppTests 

PS
在您的代碼中,您似乎引用了FindFirtFile()的Unicode版本(即FindFirstFileW() ,因為在注釋中您期望LPCWSTR ,即const wchar_t* ),但是在下面的代碼中您使用ANSI / MBCS字符串(即char* )。

我建議你在現代Windows C ++代碼中始終使用Unicode UTF-16 wchar_t*字符串:它更適合國際化,現代Win32 API只帶有Unicode版本。

另請注意,由於您使用的是C ++,因此最好使用強大的方便的字符串類 (例如,使用Microsoft Visual C ++的Unicode UTF-16字符串的std::wstring ),而不是類似C的原始字符指針。 使用API​​接口上的原始指針(因為Win32 API具有C接口),然后安全地轉換為std::wstring

在UNICODE構建中使用GetModuleFileName函數以寬字符串形式獲取可執行文件的完整文件名。

然后,搜索最后一個'\\'字符並將其替換為0。

完成。

#include <Windows.h>
#include <stdio.h>

int main( void ) {
    wchar_t szExeFullPath[ MAX_PATH ];
    if ( GetModuleFileName( NULL, szExeFullPath, _countof( szExeFullPath ) ) ) {
        wchar_t * pszLastAntiSlash = wcsrchr( szExeFullPath, L'\\' );
        if ( pszLastAntiSlash ) {
            *pszLastAntiSlash = 0;
            wprintf( L"Exe full path is %s\n", szExeFullPath );
        }
    }
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM