1 #include <stdlib.h> 2 #include <string.h> 3 #include <stdio.h> 4 #ifdef _WIN32 5 #include <windows.h> 6 #else 7 #include <unistd.h> 8 #endif 9 10 class utUtils { 11 public: get_dir_exec(char * dir,char * exec)12 void get_dir_exec(char* dir, char* exec) { 13 #ifdef _WIN32 14 char BufferFileName[MAX_PATH]; 15 memset(BufferFileName,0,MAX_PATH); 16 if (GetModuleFileName(NULL, BufferFileName, MAX_PATH)) { 17 if (exec) { 18 snprintf(exec, strlen(BufferFileName), "%s", BufferFileName); 19 } 20 21 std::string ss(BufferFileName); 22 int idx = ss.find_last_of("\\"); 23 BufferFileName[idx] = '\0'; 24 snprintf(dir, strlen(BufferFileName), "%s", BufferFileName); 25 } 26 return; 27 #else 28 char* filename = nullptr; 29 if (readlink("/proc/self/exe", dir, 1024) < 0) { 30 dir[0] = '\0'; 31 return; 32 } 33 filename = strrchr(dir, '/'); 34 if (filename == nullptr) { 35 dir[0] = '\0'; 36 return; 37 } 38 ++filename; 39 if (exec) { 40 sprintf(exec, "%s", filename); 41 } 42 43 *filename = '\0'; 44 return; 45 #endif 46 } 47 48 get_env(const std::string env)49 std::string get_env(const std::string env) { 50 51 #ifdef _WIN32 52 char* buf = nullptr; 53 size_t sz = 0; 54 if (_dupenv_s(&buf, &sz, env.c_str()) == 0 && buf != nullptr) { 55 std::string var(buf); 56 free(buf); 57 return var; 58 } else { 59 return std::string(); 60 } 61 62 #else 63 char* value = getenv(env.c_str()); 64 if (value == nullptr) { 65 return std::string(); 66 } 67 return std::string(value); 68 #endif 69 } 70 }; 71