1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.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 get_env(const std::string env)48 std::string get_env(const std::string env) { 49 50 #ifdef _WIN32 51 char *buf = nullptr; 52 size_t sz = 0; 53 if (_dupenv_s(&buf, &sz, env.c_str()) == 0 && buf != nullptr) { 54 std::string var(buf); 55 free(buf); 56 return var; 57 } else { 58 return std::string(); 59 } 60 61 #else 62 char *value = getenv(env.c_str()); 63 if (value == nullptr) { 64 return std::string(); 65 } 66 return std::string(value); 67 #endif 68 } 69 }; 70