在 C++ 中,可以使用以下两种方法获取一个软件的相对路径:\n\n1. 使用 argv[0] 获取程序的绝对路径,然后使用 std::filesystem 库来处理路径。示例代码如下:\n\ncpp\n#include <iostream>\n#include <filesystem>\n\nint main(int argc, char* argv[]) {\n if (argc > 0) {\n std::filesystem::path fullPath(argv[0]);\n std::filesystem::path relativePath = std::filesystem::relative(fullPath);\n\n std::cout << "Relative path: " << relativePath << std::endl; \n }\n\n return 0; \n}\n\n\n2. 使用 GetModuleFileName 函数获取程序的绝对路径,然后使用 std::filesystem 库来处理路径。示例代码如下:\n\ncpp\n#include <iostream>\n#include <windows.h>\n#include <filesystem>\n\nint main() {\n char buffer[MAX_PATH];\n GetModuleFileName(NULL, buffer, MAX_PATH);\n\n std::filesystem::path fullPath(buffer);\n std::filesystem::path relativePath = std::filesystem::relative(fullPath);\n\n std::cout << "Relative path: " << relativePath << std::endl; \n\n return 0; \n}\n\n\n这两种方法都使用了 std::filesystem 库来处理路径,该库提供了一系列函数和类来处理文件系统路径。请确保您的编译器支持 C++17 标准,并且已经包含了 <filesystem> 头文件。

C++ 获取软件相对路径的两种方法

原文地址: https://www.cveoy.top/t/topic/pwzY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录