inline proc get_cwd() -> char* { const int buf_size = 2048; char* res = (char*)malloc(buf_size * sizeof(char)); #ifdef _MSC_VER _getcwd(res, buf_size); #else getcwd(res, buf_size); #endif return res; } inline proc change_cwd(char* dir) -> void { #ifdef _MSC_VER _chdir(dir); #else chdir(dir); #endif } proc get_exe_dir() -> char* { #ifdef _MSC_VER DWORD last_error; DWORD result; DWORD path_size = 1024; char* path = (char*)malloc(1024); while (true) { memset(path, 0, path_size); result = GetModuleFileName(0, path, path_size - 1); last_error = GetLastError(); if (0 == result) { free(path); path = 0; break; } else if (result == path_size - 1) { free(path); /* May need to also check for ERROR_SUCCESS here if XP/2K */ if (ERROR_INSUFFICIENT_BUFFER != last_error) { path = 0; break; } path_size = path_size * 2; path = (char*)malloc(path_size); } else break; } if (!path) { fprintf(stderr, "Failure: %ld\n", last_error); return nullptr; } else { // remove the exe name, so we are only left with the path int index_in_path = -1; int last_backslash = -1; char c; while ((c = path[++index_in_path]) != '\0') { if (c == '\\') last_backslash = index_in_path; } // we are assuming there are some backslashes path[last_backslash+1] = '\0'; return path; } #else ssize_t size = 512, i, n; char *path, *temp; while (1) { size_t used; path = (char*)malloc(size); if (!path) { errno = ENOMEM; return NULL; } used = readlink("/proc/self/exe", path, size); if (used == -1) { const int saved_errno = errno; free(path); errno = saved_errno; return NULL; } else if (used < 1) { free(path); errno = EIO; return NULL; } if ((size_t)used >= size) { free(path); size = (size | 2047) + 2049; continue; } size = (size_t)used; break; } /* Find final slash. */ n = 0; for (i = 0; i < size; i++) if (path[i] == '/') n = i; /* Optimize allocated size, ensuring there is room for a final slash and a string-terminating '\0', */ temp = path; path = (char*)realloc(temp, n + 2); if (!path) { free(temp); errno = ENOMEM; return NULL; } /* and properly trim and terminate the path string. */ path[n+0] = '/'; path[n+1] = '\0'; return path; #endif }