directory.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include "directory.h"
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #ifdef _WIN32
  5. #include <Windows.h>
  6. static void set_working_directory(const char *path) {
  7. SetCurrentDirectory(path);
  8. }
  9. static void go_to_process_directory() {
  10. HMODULE hModule = GetModuleHandleW(NULL);
  11. CHAR path[MAX_PATH];
  12. GetModuleFileNameA(hModule, path, MAX_PATH);
  13. dir_set_file(path);
  14. }
  15. static char *get_working_directory() {
  16. char *new_str = malloc(sizeof(char) * MAX_PATH);
  17. GetCurrentDirectory(MAX_PATH, new_str);
  18. return new_str;
  19. }
  20. #endif
  21. void dir_set_process() {
  22. go_to_process_directory();
  23. }
  24. void dir_set(const char *path) {
  25. set_working_directory(path);
  26. }
  27. void dir_set_file(const char *path) {
  28. char *actual_path;
  29. size_t full_length = strlen(path);
  30. actual_path = malloc(sizeof(char) * (full_length + 1));
  31. strcpy(actual_path, path);
  32. size_t i = full_length - 1;
  33. while (i > 0) {
  34. if (actual_path[i] == '/' || actual_path[i] == '\\') break;
  35. actual_path[i] = '\0';
  36. --i;
  37. }
  38. actual_path[i--] = '\0';
  39. if(i != 0)
  40. set_working_directory(actual_path);
  41. free(actual_path);
  42. }
  43. char *dir_isolate_file(const char *path) {
  44. size_t length = strlen(path);
  45. size_t index = length - 1;
  46. while (index > 0) {
  47. if (path[index] == '/' || path[index] == '\\') {
  48. break;
  49. }
  50. --index;
  51. }
  52. if (path[index] == '/' || path[index] == '\\') ++index;
  53. char *new_string = malloc(sizeof(char) * (length - index + 1));
  54. strcpy(new_string, path + index);
  55. return new_string;
  56. }
  57. char *dir_get() {
  58. return get_working_directory();
  59. }