To obtain the program name, you can use the Windows API function GetModuleFileName, which can obtain the full path and file name of the current module and return an integer. Represents the number of characters actually written to the buffer. You need to pass in a character buffer and the size of the buffer to which the function writes the program name. The specific implementation code is as follows:
#include
std::string GetProgramName()
{
char buf[MAX_PATH];
GetModuleFileName(NULL, buf, MAX_PATH);
std::string fullPath(buf);
size_t pos = fullPath.find_last_of("\\");
return fullPath.substr(pos + 1);
}
To obtain a program path, you can use the path class from the filesystem library in the C++ standard library and the current_path function, which represents a file path. The current_path function returns the working directory of the current process. The specific implementation code is as follows:
#include
std::string GetProgramPath()
{
std::filesystem::path fullPath = std::filesystem::current_path();
return fullPath.string();
}
Note that the corresponding header file needs to be added to the file header.
Use these two functions to get the program name and path, as shown in the following example code:
#include
int main()
{
std::string programName = GetProgramName();
std::string programPath = GetProgramPath();
std::cout << "Program Name: " << programName << std::endl;
std::cout << "Program Path: " << programPath << std::endl;
return 0;
}