dir.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright (c) 2022 the Kongruent development team
  2. // This software is provided 'as-is', without any express or implied
  3. // warranty. In no event will the authors be held liable for any damages
  4. // arising from the use of this software.
  5. // Permission is granted to anyone to use this software for any purpose,
  6. // including commercial applications, and to alter it and redistribute it
  7. // freely, subject to the following restrictions:
  8. // 1. The origin of this software must not be misrepresented; you must not
  9. // claim that you wrote the original software. If you use this software
  10. // in a product, an acknowledgment in the product documentation would be
  11. // appreciated but is not required.
  12. // 2. Altered source versions must be plainly marked as such, and must not be
  13. // misrepresented as being the original software.
  14. // 3. This notice may not be removed or altered from any source distribution.
  15. #include "dir.h"
  16. #include <stddef.h>
  17. #include <stdio.h>
  18. #ifdef _WIN32
  19. #include <Windows.h>
  20. directory open_dir(const char *dirname) {
  21. char pattern[1024];
  22. strcpy(pattern, dirname);
  23. strcat(pattern, "\\*");
  24. WIN32_FIND_DATAA data;
  25. directory dir;
  26. dir.handle = FindFirstFileA(pattern, &data);
  27. if (dir.handle == INVALID_HANDLE_VALUE) {
  28. return dir;
  29. }
  30. FindNextFileA(dir.handle, &data);
  31. return dir;
  32. }
  33. file read_next_file(directory *dir) {
  34. WIN32_FIND_DATAA data;
  35. file file;
  36. file.valid = FindNextFileA(dir->handle, &data) != 0;
  37. if (file.valid) {
  38. strcpy(file.name, data.cFileName);
  39. }
  40. else {
  41. file.name[0] = 0;
  42. }
  43. return file;
  44. }
  45. void close_dir(directory *dir) {
  46. FindClose(dir->handle);
  47. }
  48. #else
  49. #include <string.h>
  50. #include <dirent.h>
  51. #include <sys/stat.h>
  52. #include <sys/types.h>
  53. directory open_dir(const char *dirname) {
  54. directory dir;
  55. dir.handle = opendir(dirname);
  56. return dir;
  57. }
  58. file read_next_file(directory *dir) {
  59. struct dirent *entry = readdir(dir->handle);
  60. while (entry != NULL && (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)) {
  61. entry = readdir(dir->handle);
  62. }
  63. file f;
  64. f.valid = entry != NULL;
  65. if (f.valid) {
  66. strcpy(f.name, entry->d_name);
  67. }
  68. return f;
  69. }
  70. void close_dir(directory *dir) {}
  71. #endif