0
Follow
0
View

Do you have any thoughts on this?

dianhaosu 注册会员
2023-02-28 01:08

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;
}
dentistsdp 注册会员
2023-02-28 01:08

hope to adopt

#include
#include
#include
using namespace std;
int main(int argc, char** argv)
{
    string path = argv[0];
    cout << "path:" << path << endl;
    int start = path.find_last_of("\\");
    // 从字符串尾反向搜索
    int end = path.find(".exe");
    cout << "name:" << path.substr(start, end - start);
    return 0;
}
cht9931 注册会员
2023-02-28 01:08

What do you think?

a58438331 注册会员
2023-02-28 01:08

You can use the GetFileName function in the Path class to get the program name and the GetDirectoryName function in the Path class to get the program path.
int main(int count,char* c_arg[]) this thing is just a template version and has nothing to do with the problem

About the Author

Question Info

Publish Time
2023-02-28 01:08
Update Time
2023-02-28 01:08