fileAPI.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2020 to 2022 David Forsgren Piuva
  4. //
  5. // This software is provided 'as-is', without any express or implied
  6. // warranty. In no event will the authors be held liable for any damages
  7. // arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,
  10. // including commercial applications, and to alter it and redistribute it
  11. // freely, subject to the following restrictions:
  12. //
  13. // 1. The origin of this software must not be misrepresented; you must not
  14. // claim that you wrote the original software. If you use this software
  15. // in a product, an acknowledgment in the product documentation would be
  16. // appreciated but is not required.
  17. //
  18. // 2. Altered source versions must be plainly marked as such, and must not be
  19. // misrepresented as being the original software.
  20. //
  21. // 3. This notice may not be removed or altered from any source
  22. // distribution.
  23. // Include fileAPI without falling back on local syntax implicitly.
  24. // This prevents any local syntax from being implied in functions that are supposed to use variable pathSyntax.
  25. #define NO_IMPLICIT_PATH_SYNTAX
  26. #include "fileAPI.h"
  27. #ifdef USE_MICROSOFT_WINDOWS
  28. #include <windows.h>
  29. #else
  30. #include <unistd.h>
  31. #include <sys/stat.h>
  32. #include <dirent.h>
  33. #endif
  34. #include <fstream>
  35. #include <cstdlib>
  36. #include "bufferAPI.h"
  37. namespace dsr {
  38. constexpr const char32_t* getPathSeparator(PathSyntax pathSyntax) {
  39. if (pathSyntax == PathSyntax::Windows) {
  40. return U"\\";
  41. } else if (pathSyntax == PathSyntax::Posix) {
  42. return U"/";
  43. } else {
  44. return U"?";
  45. }
  46. }
  47. #ifdef USE_MICROSOFT_WINDOWS
  48. using NativeChar = wchar_t; // UTF-16
  49. static const CharacterEncoding nativeEncoding = CharacterEncoding::BOM_UTF16LE;
  50. #define FILE_ACCESS_FUNCTION _wfopen
  51. #define FILE_ACCESS_SELECTION (write ? L"wb" : L"rb")
  52. List<String> file_impl_getInputArguments() {
  53. // Get a pointer to static memory with the command
  54. LPWSTR cmd = GetCommandLineW();
  55. // Split the arguments into an array of arguments
  56. int argc = 0;
  57. LPWSTR *argv = CommandLineToArgvW(cmd, &argc);
  58. // Convert the arguments into dsr::List<dsr::String>
  59. List<String> args = file_impl_convertInputArguments(argc, (void**)argv);
  60. // Free the native list of arguments
  61. LocalFree(argv);
  62. return args;
  63. }
  64. #else
  65. using NativeChar = char; // UTF-8
  66. static const CharacterEncoding nativeEncoding = CharacterEncoding::BOM_UTF8;
  67. #define FILE_ACCESS_FUNCTION fopen
  68. #define FILE_ACCESS_SELECTION (write ? "wb" : "rb")
  69. List<String> file_impl_getInputArguments() { return List<String>(); }
  70. #endif
  71. // Length of fixed size buffers.
  72. const int maxLength = 512;
  73. static const NativeChar* toNativeString(const ReadableString &filename, Buffer &buffer) {
  74. buffer = string_saveToMemory(filename, nativeEncoding, LineEncoding::CrLf, false, true);
  75. return (const NativeChar*)buffer_dangerous_getUnsafeData(buffer);
  76. }
  77. static String fromNativeString(const NativeChar *text) {
  78. return string_dangerous_decodeFromData(text, nativeEncoding);
  79. }
  80. List<String> file_impl_convertInputArguments(int argn, void **argv) {
  81. List<String> result;
  82. result.reserve(argn);
  83. for (int a = 0; a < argn; a++) {
  84. result.push(fromNativeString((NativeChar*)(argv[a])));
  85. }
  86. return result;
  87. }
  88. static FILE* accessFile(const ReadableString &filename, bool write) {
  89. Buffer buffer;
  90. return FILE_ACCESS_FUNCTION(toNativeString(filename, buffer), FILE_ACCESS_SELECTION);
  91. }
  92. Buffer file_loadBuffer(const ReadableString& filename, bool mustExist) {
  93. String modifiedFilename = file_optimizePath(filename, LOCAL_PATH_SYNTAX);
  94. FILE *file = accessFile(modifiedFilename, false);
  95. if (file != nullptr) {
  96. // Get the file's size by going to the end, measuring, and going back
  97. fseek(file, 0L, SEEK_END);
  98. int64_t fileSize = ftell(file);
  99. rewind(file);
  100. // Allocate a buffer of the file's size
  101. Buffer buffer = buffer_create(fileSize);
  102. fread((void*)buffer_dangerous_getUnsafeData(buffer), fileSize, 1, file);
  103. fclose(file);
  104. return buffer;
  105. } else {
  106. if (mustExist) {
  107. throwError(U"Failed to load ", modifiedFilename, ".\n");
  108. }
  109. // If the file cound not be found and opened, an empty buffer is returned
  110. return Buffer();
  111. }
  112. }
  113. bool file_saveBuffer(const ReadableString& filename, Buffer buffer, bool mustWork) {
  114. String modifiedFilename = file_optimizePath(filename, LOCAL_PATH_SYNTAX);
  115. if (!buffer_exists(buffer)) {
  116. if (mustWork) {
  117. throwError(U"buffer_save: Can't save a buffer that don't exist to a file.\n");
  118. }
  119. return false;
  120. } else {
  121. FILE *file = accessFile(modifiedFilename, true);
  122. if (file != nullptr) {
  123. fwrite((void*)buffer_dangerous_getUnsafeData(buffer), buffer_getSize(buffer), 1, file);
  124. fclose(file);
  125. } else {
  126. if (mustWork) {
  127. throwError("Failed to save ", modifiedFilename, ".\n");
  128. }
  129. return false;
  130. }
  131. }
  132. // Success if there are no errors.
  133. return true;
  134. }
  135. const char32_t* file_separator() {
  136. return getPathSeparator(LOCAL_PATH_SYNTAX);
  137. }
  138. inline bool isSeparator(DsrChar c) {
  139. return c == U'\\' || c == U'/';
  140. }
  141. // Returns the index of the first / or \ in path, or defaultIndex if none existed.
  142. static int64_t getFirstSeparator(const ReadableString &path, int64_t defaultIndex) {
  143. for (int64_t i = 0; i < string_length(path); i++) {
  144. DsrChar c = path[i];
  145. if (isSeparator(c)) {
  146. return i;
  147. }
  148. }
  149. return defaultIndex;
  150. }
  151. // Returns the index of the last / or \ in path, or defaultIndex if none existed.
  152. static int64_t getLastSeparator(const ReadableString &path, int64_t defaultIndex) {
  153. for (int64_t i = string_length(path) - 1; i >= 0; i--) {
  154. DsrChar c = path[i];
  155. if (isSeparator(c)) {
  156. return i;
  157. }
  158. }
  159. return defaultIndex;
  160. }
  161. String file_optimizePath(const ReadableString &path, PathSyntax pathSyntax) {
  162. String result; // The final output being appended.
  163. String currentEntry; // The current entry.
  164. bool hadSeparator = false;
  165. bool hadContent = false;
  166. int64_t inputLength = string_length(path);
  167. string_reserve(result, inputLength);
  168. // Read null terminator from one element outside of the path to allow concluding an entry not followed by any separator.
  169. // The null terminator is not actually stored, but reading out of bound gives a null terminator.
  170. for (int64_t i = 0; i <= inputLength; i++) {
  171. DsrChar c = path[i];
  172. bool separator = isSeparator(c);
  173. if (separator || i == inputLength) {
  174. bool appendEntry = true;
  175. bool appendSeparator = separator;
  176. if (hadSeparator) {
  177. if (hadContent && string_length(currentEntry) == 0) {
  178. // Reduce non-leading // into / by skipping "" entries.
  179. // Any leading multiples of slashes have their count preserved, because some systems use them to indicate special use cases.
  180. appendEntry = false;
  181. appendSeparator = false;
  182. } else if (string_match(currentEntry, U".")) {
  183. // Reduce /./ into / by skipping "." entries.
  184. appendEntry = false;
  185. appendSeparator = false;
  186. } else if (string_match(currentEntry, U"..")) {
  187. // Reduce the parent directory against the reverse ".." entry.
  188. result = file_getRelativeParentFolder(result, pathSyntax);
  189. if (string_match(result, U"?")) {
  190. return U"?";
  191. }
  192. appendEntry = false;
  193. }
  194. }
  195. if (appendEntry) {
  196. string_append(result, string_removeOuterWhiteSpace(currentEntry));
  197. }
  198. if (appendSeparator) {
  199. string_append(result, getPathSeparator(pathSyntax));
  200. }
  201. currentEntry = U"";
  202. if (separator) {
  203. hadSeparator = true;
  204. }
  205. } else {
  206. string_appendChar(currentEntry, c);
  207. hadContent = true;
  208. }
  209. }
  210. // Remove trailing separators if we had content.
  211. if (hadSeparator && hadContent) {
  212. int64_t lastNonSeparator = -1;
  213. for (int64_t i = string_length(result) - 1; i >= 0; i--) {
  214. if (!isSeparator(result[i])) {
  215. lastNonSeparator = i;
  216. break;
  217. }
  218. }
  219. result = string_until(result, lastNonSeparator);
  220. }
  221. return result;
  222. }
  223. ReadableString file_getPathlessName(const ReadableString &path) {
  224. return string_after(path, getLastSeparator(path, -1));
  225. }
  226. ReadableString file_getExtension(const String& filename) {
  227. int64_t lastDotIndex = string_findLast(filename, U'.');
  228. int64_t lastSeparatorIndex = getLastSeparator(filename, -1);
  229. // Only use the last dot if there is no folder separator after it.
  230. if (lastDotIndex != -1 && lastSeparatorIndex < lastDotIndex) {
  231. return string_removeOuterWhiteSpace(string_after(filename, lastDotIndex));
  232. } else {
  233. return U"";
  234. }
  235. }
  236. String file_getRelativeParentFolder(const ReadableString &path, PathSyntax pathSyntax) {
  237. String optimizedPath = file_optimizePath(path, pathSyntax);
  238. if (string_length(optimizedPath) == 0) {
  239. // Use .. to go outside of the current directory.
  240. return U"..";
  241. } else if (string_match(file_getPathlessName(optimizedPath), U"?")) {
  242. // From unknown to unknown.
  243. return U"?";
  244. } else if (file_isRoot(optimizedPath, false, pathSyntax)) {
  245. // If it's the known true root, then we know that it does not have a parent and must fail.
  246. return U"?";
  247. } else if (file_isRoot(optimizedPath, true, pathSyntax)) {
  248. // If it's an alias for an arbitrary folder, use .. to leave it.
  249. return file_combinePaths(optimizedPath, U"..", pathSyntax);
  250. } else if (string_match(file_getPathlessName(optimizedPath), U"..")) {
  251. // Add more dots to the path.
  252. return file_combinePaths(optimizedPath, U"..", pathSyntax);
  253. } else {
  254. // Inside of something.
  255. int64_t lastSeparator = getLastSeparator(optimizedPath, 0);
  256. if (pathSyntax == PathSyntax::Windows) {
  257. // Return everything before the last separator.
  258. return string_before(optimizedPath, lastSeparator);
  259. } else { // PathSyntax::Posix
  260. if (file_hasRoot(path, false, pathSyntax) && lastSeparator == 0) {
  261. // Keep the absolute root.
  262. return U"/";
  263. } else {
  264. // Keep everything before the last separator.
  265. return string_before(optimizedPath, lastSeparator);
  266. }
  267. }
  268. }
  269. }
  270. String file_getTheoreticalAbsoluteParentFolder(const ReadableString &path, const ReadableString &currentPath, PathSyntax pathSyntax) {
  271. if (file_hasRoot(path, true, LOCAL_PATH_SYNTAX)) {
  272. // Absolute paths should be treated the same as a theoretical path.
  273. return file_getRelativeParentFolder(path, pathSyntax);
  274. } else {
  275. // If the input is not absolute, convert it before taking the parent directory.
  276. return file_getRelativeParentFolder(file_getTheoreticalAbsolutePath(path, currentPath, pathSyntax), pathSyntax);
  277. }
  278. }
  279. String file_getAbsoluteParentFolder(const ReadableString &path) {
  280. return file_getTheoreticalAbsoluteParentFolder(path, file_getCurrentPath(), LOCAL_PATH_SYNTAX);
  281. }
  282. bool file_isRoot(const ReadableString &path, bool treatHomeFolderAsRoot, PathSyntax pathSyntax) {
  283. ReadableString cleanPath = string_removeOuterWhiteSpace(path);
  284. int64_t length = string_length(cleanPath);
  285. if (length == 0) {
  286. // Relative path is not a root.
  287. return false;
  288. } else if (length == 1) {
  289. DsrChar c = cleanPath[0];
  290. if (pathSyntax == PathSyntax::Windows) {
  291. return c == U'\\'; // Implicit drive root.
  292. } else { // PathSyntax::Posix
  293. return c == U'/' || (c == U'~' && treatHomeFolderAsRoot); // Root over all drives or home folder.
  294. }
  295. } else {
  296. if (pathSyntax == PathSyntax::Windows && cleanPath[length - 1] == U':') {
  297. // C:, D:, ...
  298. return true;
  299. } else {
  300. return false;
  301. }
  302. }
  303. }
  304. bool file_hasRoot(const ReadableString &path, bool treatHomeFolderAsRoot, PathSyntax pathSyntax) {
  305. int64_t firstSeparator = getFirstSeparator(path, -1);
  306. if (firstSeparator == -1) {
  307. // If there is no separator, path has a root if it is a root.
  308. return file_isRoot(path, treatHomeFolderAsRoot, pathSyntax);
  309. } else if (firstSeparator == 0) {
  310. // Starting with a separator. Either an implicit drive on Windows or the whole system's root on Posix.
  311. return true;
  312. } else {
  313. // Has a root if the first entry before the first slash is a root.
  314. return file_isRoot(string_before(path, firstSeparator), treatHomeFolderAsRoot, pathSyntax);
  315. }
  316. }
  317. bool file_setCurrentPath(const ReadableString &path) {
  318. Buffer buffer;
  319. const NativeChar *nativePath = toNativeString(file_optimizePath(path, LOCAL_PATH_SYNTAX), buffer);
  320. #ifdef USE_MICROSOFT_WINDOWS
  321. return SetCurrentDirectoryW(nativePath);
  322. #else
  323. return chdir(nativePath) == 0;
  324. #endif
  325. }
  326. String file_getCurrentPath() {
  327. #ifdef USE_MICROSOFT_WINDOWS
  328. NativeChar resultBuffer[maxLength + 1] = {0};
  329. GetCurrentDirectoryW(maxLength, resultBuffer);
  330. return fromNativeString(resultBuffer);
  331. #else
  332. NativeChar resultBuffer[maxLength + 1] = {0};
  333. getcwd(resultBuffer, maxLength);
  334. return fromNativeString(resultBuffer);
  335. #endif
  336. }
  337. String file_followSymbolicLink(const ReadableString &path, bool mustExist) {
  338. String modifiedPath = file_optimizePath(path, LOCAL_PATH_SYNTAX);
  339. Buffer buffer;
  340. const NativeChar *nativePath = toNativeString(modifiedPath, buffer);
  341. #ifdef USE_MICROSOFT_WINDOWS
  342. // TODO: Is there anything that can be used as a symbolic link on Windows?
  343. #else
  344. NativeChar resultBuffer[maxLength + 1] = {0};
  345. if (readlink(nativePath, resultBuffer, maxLength) != -1) {
  346. return fromNativeString(resultBuffer);
  347. }
  348. #endif
  349. if (mustExist) { throwError(U"The symbolic link ", path, " could not be found!\n"); }
  350. return U"?";
  351. }
  352. String file_getApplicationFolder(bool allowFallback) {
  353. #ifdef USE_MICROSOFT_WINDOWS
  354. NativeChar resultBuffer[maxLength + 1] = {0};
  355. GetModuleFileNameW(nullptr, resultBuffer, maxLength);
  356. return file_getRelativeParentFolder(fromNativeString(resultBuffer), LOCAL_PATH_SYNTAX);
  357. #else
  358. NativeChar resultBuffer[maxLength + 1] = {0};
  359. if (readlink("/proc/self/exe", resultBuffer, maxLength) != -1) {
  360. // Linux detected
  361. return file_getAbsoluteParentFolder(fromNativeString(resultBuffer));
  362. } else if (readlink("/proc/curproc/file", resultBuffer, maxLength) != -1) {
  363. // BSD detected
  364. return file_getAbsoluteParentFolder(fromNativeString(resultBuffer));
  365. } else if (readlink("/proc/self/path/a.out", resultBuffer, maxLength) != -1) {
  366. // Solaris detected
  367. return file_getAbsoluteParentFolder(fromNativeString(resultBuffer));
  368. } else if (allowFallback) {
  369. return file_getCurrentPath();
  370. } else {
  371. throwError("file_getApplicationFolder is not implemented for the current system!\n");
  372. return U"";
  373. }
  374. #endif
  375. }
  376. String file_combinePaths(const ReadableString &a, const ReadableString &b, PathSyntax pathSyntax) {
  377. ReadableString cleanA = string_removeOuterWhiteSpace(a);
  378. ReadableString cleanB = string_removeOuterWhiteSpace(b);
  379. int64_t lengthA = string_length(cleanA);
  380. int64_t lengthB = string_length(cleanB);
  381. if (file_hasRoot(b, true, pathSyntax)) {
  382. // Restarting from root or home folder.
  383. return cleanB;
  384. } else if (lengthA == 0) {
  385. // Ignoring initial relative path, so that relative paths are not suddenly moved to the root by a new separator.
  386. return cleanB;
  387. } else if (lengthB == 0) {
  388. // Ignoring initial relative path, so that relative paths are not suddenly moved to the root by a new separator.
  389. return cleanA;
  390. } else {
  391. if (isSeparator(a[lengthA - 1])) {
  392. // Already ending with a separator.
  393. return string_combine(cleanA, cleanB);
  394. } else {
  395. // Combine using a separator.
  396. return string_combine(cleanA, getPathSeparator(pathSyntax), cleanB);
  397. }
  398. }
  399. }
  400. // Returns path with the drive letter applied from currentPath if missing in path.
  401. // Used for converting drive relative paths into true absolute paths on MS-Windows.
  402. static String applyDriveLetter(const ReadableString &path, const ReadableString &currentPath) {
  403. // Convert implicit drive into a named drive.
  404. printText("applyDriveLetter(", path, ", ", currentPath, ")\n");
  405. if (path[0] == U'\\') {
  406. printText(" Implicit drive.\n");
  407. int64_t colonIndex = string_findFirst(currentPath, U':', -1);
  408. if (colonIndex == -1) {
  409. printText(" No colon found!\n");
  410. return U"?";
  411. } else {
  412. // Get the drive letter from the current path.
  413. String drive = string_until(currentPath, colonIndex);
  414. printText(" drive = ", drive, "\n");
  415. return string_combine(drive, path);
  416. }
  417. } else {
  418. printText(" Already absolute.\n");
  419. // Already absolute.
  420. return path;
  421. }
  422. }
  423. String file_getTheoreticalAbsolutePath(const ReadableString &path, const ReadableString &currentPath, PathSyntax pathSyntax) {
  424. // Home folders are absolute enough, because we don't want to lose the account ambiguity by mangling it into hardcoded usernames.
  425. if (file_hasRoot(path, true, pathSyntax)) {
  426. if (pathSyntax == PathSyntax::Windows) {
  427. // Make sure that no drive letter is missing.
  428. return applyDriveLetter(file_optimizePath(path, pathSyntax), currentPath);
  429. } else {
  430. // Already absolute.
  431. return file_optimizePath(path, pathSyntax);
  432. }
  433. } else {
  434. // Convert from relative path.
  435. return file_optimizePath(file_combinePaths(currentPath, path, pathSyntax), pathSyntax);
  436. }
  437. }
  438. String file_getAbsolutePath(const ReadableString &path) {
  439. return file_getTheoreticalAbsolutePath(path, file_getCurrentPath(), LOCAL_PATH_SYNTAX);
  440. }
  441. int64_t file_getFileSize(const ReadableString& filename) {
  442. int64_t result = -1;
  443. String modifiedFilename = file_optimizePath(filename, LOCAL_PATH_SYNTAX);
  444. Buffer buffer;
  445. const NativeChar *nativePath = toNativeString(modifiedFilename, buffer);
  446. #ifdef USE_MICROSOFT_WINDOWS
  447. LARGE_INTEGER fileSize;
  448. HANDLE fileHandle = CreateFileW(nativePath, 0, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  449. if (fileHandle != INVALID_HANDLE_VALUE) {
  450. if (GetFileSizeEx(fileHandle, &fileSize)) {
  451. result = fileSize.QuadPart;
  452. }
  453. CloseHandle(fileHandle);
  454. }
  455. #else
  456. struct stat info;
  457. if (stat(nativePath, &info) == 0) {
  458. result = info.st_size;
  459. }
  460. #endif
  461. return result;
  462. }
  463. String& string_toStreamIndented(String& target, const EntryType& source, const ReadableString& indentation) {
  464. string_append(target, indentation);
  465. if (source == EntryType::NotFound) {
  466. string_append(target, U"not found");
  467. } else if (source == EntryType::File) {
  468. string_append(target, U"a file");
  469. } else if (source == EntryType::Folder) {
  470. string_append(target, U"a folder");
  471. } else if (source == EntryType::SymbolicLink) {
  472. string_append(target, U"a symbolic link");
  473. } else {
  474. string_append(target, U"unhandled");
  475. }
  476. return target;
  477. }
  478. EntryType file_getEntryType(const ReadableString &path) {
  479. EntryType result = EntryType::NotFound;
  480. String optimizedPath = file_optimizePath(path, LOCAL_PATH_SYNTAX);
  481. Buffer buffer;
  482. const NativeChar *nativePath = toNativeString(optimizedPath, buffer);
  483. #ifdef USE_MICROSOFT_WINDOWS
  484. DWORD dwAttrib = GetFileAttributesW(nativePath);
  485. if (dwAttrib != INVALID_FILE_ATTRIBUTES) {
  486. if (dwAttrib & FILE_ATTRIBUTE_DIRECTORY) {
  487. result = EntryType::Folder;
  488. } else {
  489. result = EntryType::File;
  490. }
  491. }
  492. #else
  493. struct stat info;
  494. int errorCode = stat(nativePath, &info);
  495. if (errorCode == 0) {
  496. if (S_ISDIR(info.st_mode)) {
  497. result = EntryType::Folder;
  498. } else if (S_ISREG(info.st_mode)) {
  499. result = EntryType::File;
  500. } else if (S_ISLNK(info.st_mode)) {
  501. result = EntryType::SymbolicLink;
  502. } else {
  503. result = EntryType::UnhandledType;
  504. }
  505. }
  506. #endif
  507. return result;
  508. }
  509. bool file_getFolderContent(const ReadableString& folderPath, std::function<void(const ReadableString& entryPath, const ReadableString& entryName, EntryType entryType)> action) {
  510. String optimizedPath = file_optimizePath(folderPath, LOCAL_PATH_SYNTAX);
  511. #ifdef USE_MICROSOFT_WINDOWS
  512. String pattern = file_combinePaths(optimizedPath, U"*.*", LOCAL_PATH_SYNTAX);
  513. Buffer buffer;
  514. const NativeChar *nativePattern = toNativeString(pattern, buffer);
  515. WIN32_FIND_DATAW findData;
  516. HANDLE findHandle = FindFirstFileW(nativePattern, &findData);
  517. if (findHandle == INVALID_HANDLE_VALUE) {
  518. return false;
  519. } else {
  520. while (true) {
  521. String entryName = fromNativeString(findData.cFileName);
  522. if (!string_match(entryName, U".") && !string_match(entryName, U"..")) {
  523. String entryPath = file_combinePaths(optimizedPath, entryName, LOCAL_PATH_SYNTAX);
  524. EntryType entryType = EntryType::UnhandledType;
  525. if(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  526. entryType = EntryType::Folder;
  527. } else {
  528. entryType = EntryType::File;
  529. }
  530. action(entryPath, entryName, entryType);
  531. }
  532. if (!FindNextFileW(findHandle, &findData)) { break; }
  533. }
  534. FindClose(findHandle);
  535. }
  536. #else
  537. Buffer buffer;
  538. const NativeChar *nativePath = toNativeString(optimizedPath, buffer);
  539. DIR *directory = opendir(nativePath);
  540. if (directory == nullptr) {
  541. return false;
  542. } else {
  543. while (true) {
  544. dirent *entry = readdir(directory);
  545. if (entry != nullptr) {
  546. String entryName = fromNativeString(entry->d_name);
  547. if (!string_match(entryName, U".") && !string_match(entryName, U"..")) {
  548. String entryPath = file_combinePaths(optimizedPath, entryName, LOCAL_PATH_SYNTAX);
  549. EntryType entryType = file_getEntryType(entryPath);
  550. action(entryPath, entryName, entryType);
  551. }
  552. } else {
  553. break;
  554. }
  555. }
  556. }
  557. closedir(directory);
  558. #endif
  559. return true;
  560. }
  561. }