标签:__ currentExecFilePath std c++ 获取 地址 path size
# 在使用cpp的很多时候,不像其他语言例如Python Java.这些跨平台语言获取当前执行的文件实际地址(实现工作环境地址)是非常方便的.
. Python获取当前执行文件的实际地址
import os print(os.path.realpath(__file__))
. Java获取当前执行文件的实际工作环境地址
package com.zhilu.resolvespring.util; /** * @author zhilu * @version jdk1.8 * * 当前工作环境的实际地址。 */ public class GetEnvironmentPath { public static void main(String[] args) { String str = System.getProperty("user.dir"); System.out.println("path:" + str); } }
# Cpp 因为不是跨平台语言并且每种主流的操作系统获取当前执行文件的实际地址的头文件和函数不相同。在开发时有获取当前执行文件的实际地址需求往往比较难以coding,对此在这里整理一下。
// // Created by zhilu on 2022/6/26. // /** * @author zhilu * @version -std=c++11 * * 跨平台获取当前执行的文件地址(exec) */ #include <iostream> #if _WIN32 #include <windows.h> #elif __linux__ #include <unistd.h> #elif __APPLE__ #include <mach-o/dyld.h> #endif // 值返回,不将地址进行返回. std::string getCurrentExecFilePath() { char path[512]; unsigned size = 512; char *currentExecFilePath; currentExecFilePath = static_cast<char *>(malloc(sizeof(char))); if (!currentExecFilePath) { std::cout << "malloc failed" << std::endl; return {}; } // 对于Windows操作系统来说 #if _WIN32 // GetModuleFileName()函数在头文件#include <windows.h>下 GetModuleFileName(nullptr, path, size); path[size] = '\0'; currentExecFilePath = path; // 对于Linux操作系统 #elif __linux__ // readlink()函数在头文件<unistd.h>下 int n = readlink("/proc/self/exe", path, size); std::string path_string; path[n] = '\0'; if(n > 0 && n < size){ currentExecFilePath = path; } // 对于Mac os操作系统 #elif __APPLE__ // _NSGetExecutablePath()函数在头文件<mach-o/dyld.h>下 _NSGetExecutablePath(path, &size); path[size] = '\0'; currentExecFilePath = path; #endif return currentExecFilePath; } int main() { std::cout << getCurrentExecFilePath() << std::endl; }
# 以上code在三种平台测试后没有问题。请放心食用。
标签:__,currentExecFilePath,std,c++,获取,地址,path,size 来源: https://www.cnblogs.com/luzhi0324/p/16414881.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。