我想我的问题是-如何将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
在您的代码中,您似乎引用的Unicode版本FindFirtFile()
(即FindFirstFileW()
,因为在注释中期望使用LPCWSTR
,即const wchar_t*
),但是随后在以下代码中使用ANSI / MBCS字符串(即char*
)。
我建议您始终在现代Windows C ++代码中使用Unicode UTF-16wchar_t*
字符串:更好地进行国际化,并且现代Win32 API仅随附Unicode版本。
还要注意,由于使用的是C ++,最好使用健壮且方便的字符串类(例如,std::wstring
对于使用Microsoft Visual C ++的Unicode UTF-16字符串),而不是使用类似C的原始字符指针。在API接口上使用原始指针(因为Win32 API具有C接口),然后安全地转换为std::wstring
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句