fileAPI.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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. String file_getRelativeParentFolder(const ReadableString &path, PathSyntax pathSyntax) {
  227. String optimizedPath = file_optimizePath(path, pathSyntax);
  228. if (string_length(optimizedPath) == 0) {
  229. // Use .. to go outside of the current directory.
  230. return U"..";
  231. } else if (string_match(file_getPathlessName(optimizedPath), U"?")) {
  232. // From unknown to unknown.
  233. return U"?";
  234. } else if (file_isRoot(optimizedPath, false, pathSyntax)) {
  235. // If it's the known true root, then we know that it does not have a parent and must fail.
  236. return U"?";
  237. } else if (file_isRoot(optimizedPath, true, pathSyntax)) {
  238. // If it's an alias for an arbitrary folder, use .. to leave it.
  239. return file_combinePaths(optimizedPath, U"..", pathSyntax);
  240. } else if (string_match(file_getPathlessName(optimizedPath), U"..")) {
  241. // Add more dots to the path.
  242. return file_combinePaths(optimizedPath, U"..", pathSyntax);
  243. } else {
  244. // Inside of something.
  245. int64_t lastSeparator = getLastSeparator(optimizedPath, 0);
  246. if (pathSyntax == PathSyntax::Windows) {
  247. // Return everything before the last separator.
  248. return string_before(optimizedPath, lastSeparator);
  249. } else { // PathSyntax::Posix
  250. if (file_hasRoot(path, false, pathSyntax) && lastSeparator == 0) {
  251. // Keep the absolute root.
  252. return U"/";
  253. } else {
  254. // Keep everything before the last separator.
  255. return string_before(optimizedPath, lastSeparator);
  256. }
  257. }
  258. }
  259. }
  260. String file_getTheoreticalAbsoluteParentFolder(const ReadableString &path, const ReadableString &currentPath, PathSyntax pathSyntax) {
  261. if (file_hasRoot(path, true, LOCAL_PATH_SYNTAX)) {
  262. // Absolute paths should be treated the same as a theoretical path.
  263. return file_getRelativeParentFolder(path, pathSyntax);
  264. } else {
  265. // If the input is not absolute, convert it before taking the parent directory.
  266. return file_getRelativeParentFolder(file_getTheoreticalAbsolutePath(path, currentPath, pathSyntax), pathSyntax);
  267. }
  268. }
  269. String file_getAbsoluteParentFolder(const ReadableString &path) {
  270. return file_getTheoreticalAbsoluteParentFolder(path, file_getCurrentPath(), LOCAL_PATH_SYNTAX);
  271. }
  272. bool file_isRoot(const ReadableString &path, bool treatHomeFolderAsRoot, PathSyntax pathSyntax) {
  273. ReadableString cleanPath = string_removeOuterWhiteSpace(path);
  274. int64_t length = string_length(cleanPath);
  275. if (length == 0) {
  276. // Relative path is not a root.
  277. return false;
  278. } else if (length == 1) {
  279. DsrChar c = cleanPath[0];
  280. if (pathSyntax == PathSyntax::Windows) {
  281. return c == U'\\'; // Implicit drive root.
  282. } else { // PathSyntax::Posix
  283. return c == U'/' || (c == U'~' && treatHomeFolderAsRoot); // Root over all drives or home folder.
  284. }
  285. } else {
  286. if (pathSyntax == PathSyntax::Windows && cleanPath[length - 1] == U':') {
  287. // C:, D:, ...
  288. return true;
  289. } else {
  290. return false;
  291. }
  292. }
  293. }
  294. bool file_hasRoot(const ReadableString &path, bool treatHomeFolderAsRoot, PathSyntax pathSyntax) {
  295. int64_t firstSeparator = getFirstSeparator(path, -1);
  296. if (firstSeparator == -1) {
  297. // If there is no separator, path has a root if it is a root.
  298. return file_isRoot(path, treatHomeFolderAsRoot, pathSyntax);
  299. } else if (firstSeparator == 0) {
  300. // Starting with a separator. Either an implicit drive on Windows or the whole system's root on Posix.
  301. return true;
  302. } else {
  303. // Has a root if the first entry before the first slash is a root.
  304. return file_isRoot(string_before(path, firstSeparator), treatHomeFolderAsRoot, pathSyntax);
  305. }
  306. }
  307. bool file_setCurrentPath(const ReadableString &path) {
  308. Buffer buffer;
  309. const NativeChar *nativePath = toNativeString(file_optimizePath(path, LOCAL_PATH_SYNTAX), buffer);
  310. #ifdef USE_MICROSOFT_WINDOWS
  311. return SetCurrentDirectoryW(nativePath);
  312. #else
  313. return chdir(nativePath) == 0;
  314. #endif
  315. }
  316. String file_getCurrentPath() {
  317. #ifdef USE_MICROSOFT_WINDOWS
  318. NativeChar resultBuffer[maxLength + 1] = {0};
  319. GetCurrentDirectoryW(maxLength, resultBuffer);
  320. return fromNativeString(resultBuffer);
  321. #else
  322. NativeChar resultBuffer[maxLength + 1] = {0};
  323. getcwd(resultBuffer, maxLength);
  324. return fromNativeString(resultBuffer);
  325. #endif
  326. }
  327. String file_followSymbolicLink(const ReadableString &path, bool mustExist) {
  328. String modifiedPath = file_optimizePath(path, LOCAL_PATH_SYNTAX);
  329. Buffer buffer;
  330. const NativeChar *nativePath = toNativeString(modifiedPath, buffer);
  331. #ifdef USE_MICROSOFT_WINDOWS
  332. // TODO: Is there anything that can be used as a symbolic link on Windows?
  333. #else
  334. NativeChar resultBuffer[maxLength + 1] = {0};
  335. if (readlink(nativePath, resultBuffer, maxLength) != -1) {
  336. return fromNativeString(resultBuffer);
  337. }
  338. #endif
  339. if (mustExist) { throwError(U"The symbolic link ", path, " could not be found!\n"); }
  340. return U"?";
  341. }
  342. String file_getApplicationFolder(bool allowFallback) {
  343. #ifdef USE_MICROSOFT_WINDOWS
  344. NativeChar resultBuffer[maxLength + 1] = {0};
  345. GetModuleFileNameW(nullptr, resultBuffer, maxLength);
  346. return file_getRelativeParentFolder(fromNativeString(resultBuffer), LOCAL_PATH_SYNTAX);
  347. #else
  348. NativeChar resultBuffer[maxLength + 1] = {0};
  349. if (readlink("/proc/self/exe", resultBuffer, maxLength) != -1) {
  350. // Linux detected
  351. return file_getAbsoluteParentFolder(fromNativeString(resultBuffer));
  352. } else if (readlink("/proc/curproc/file", resultBuffer, maxLength) != -1) {
  353. // BSD detected
  354. return file_getAbsoluteParentFolder(fromNativeString(resultBuffer));
  355. } else if (readlink("/proc/self/path/a.out", resultBuffer, maxLength) != -1) {
  356. // Solaris detected
  357. return file_getAbsoluteParentFolder(fromNativeString(resultBuffer));
  358. } else if (allowFallback) {
  359. return file_getCurrentPath();
  360. } else {
  361. throwError("file_getApplicationFolder is not implemented for the current system!\n");
  362. return U"";
  363. }
  364. #endif
  365. }
  366. String file_combinePaths(const ReadableString &a, const ReadableString &b, PathSyntax pathSyntax) {
  367. ReadableString cleanA = string_removeOuterWhiteSpace(a);
  368. ReadableString cleanB = string_removeOuterWhiteSpace(b);
  369. int64_t lengthA = string_length(cleanA);
  370. int64_t lengthB = string_length(cleanB);
  371. if (file_hasRoot(b, true, pathSyntax)) {
  372. // Restarting from root or home folder.
  373. return cleanB;
  374. } else if (lengthA == 0) {
  375. // Ignoring initial relative path, so that relative paths are not suddenly moved to the root by a new separator.
  376. return cleanB;
  377. } else if (lengthB == 0) {
  378. // Ignoring initial relative path, so that relative paths are not suddenly moved to the root by a new separator.
  379. return cleanA;
  380. } else {
  381. if (isSeparator(a[lengthA - 1])) {
  382. // Already ending with a separator.
  383. return string_combine(cleanA, cleanB);
  384. } else {
  385. // Combine using a separator.
  386. return string_combine(cleanA, getPathSeparator(pathSyntax), cleanB);
  387. }
  388. }
  389. }
  390. // Returns path with the drive letter applied from currentPath if missing in path.
  391. // Used for converting drive relative paths into true absolute paths on MS-Windows.
  392. static String applyDriveLetter(const ReadableString &path, const ReadableString &currentPath) {
  393. // Convert implicit drive into a named drive.
  394. printText("applyDriveLetter(", path, ", ", currentPath, ")\n");
  395. if (path[0] == U'\\') {
  396. printText(" Implicit drive.\n");
  397. int64_t colonIndex = string_findFirst(currentPath, U':', -1);
  398. if (colonIndex == -1) {
  399. printText(" No colon found!\n");
  400. return U"?";
  401. } else {
  402. // Get the drive letter from the current path.
  403. String drive = string_until(currentPath, colonIndex);
  404. printText(" drive = ", drive, "\n");
  405. return string_combine(drive, path);
  406. }
  407. } else {
  408. printText(" Already absolute.\n");
  409. // Already absolute.
  410. return path;
  411. }
  412. }
  413. String file_getTheoreticalAbsolutePath(const ReadableString &path, const ReadableString &currentPath, PathSyntax pathSyntax) {
  414. // Home folders are absolute enough, because we don't want to lose the account ambiguity by mangling it into hardcoded usernames.
  415. if (file_hasRoot(path, true, pathSyntax)) {
  416. if (pathSyntax == PathSyntax::Windows) {
  417. // Make sure that no drive letter is missing.
  418. return applyDriveLetter(file_optimizePath(path, pathSyntax), currentPath);
  419. } else {
  420. // Already absolute.
  421. return file_optimizePath(path, pathSyntax);
  422. }
  423. } else {
  424. // Convert from relative path.
  425. return file_optimizePath(file_combinePaths(currentPath, path, pathSyntax), pathSyntax);
  426. }
  427. }
  428. String file_getAbsolutePath(const ReadableString &path) {
  429. return file_getTheoreticalAbsolutePath(path, file_getCurrentPath(), LOCAL_PATH_SYNTAX);
  430. }
  431. int64_t file_getFileSize(const ReadableString& filename) {
  432. int64_t result = -1;
  433. String modifiedFilename = file_optimizePath(filename, LOCAL_PATH_SYNTAX);
  434. Buffer buffer;
  435. const NativeChar *nativePath = toNativeString(modifiedFilename, buffer);
  436. #ifdef USE_MICROSOFT_WINDOWS
  437. LARGE_INTEGER fileSize;
  438. HANDLE fileHandle = CreateFileW(nativePath, 0, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  439. if (fileHandle != INVALID_HANDLE_VALUE) {
  440. if (GetFileSizeEx(fileHandle, &fileSize)) {
  441. result = fileSize.QuadPart;
  442. }
  443. CloseHandle(fileHandle);
  444. }
  445. #else
  446. struct stat info;
  447. if (stat(nativePath, &info) == 0) {
  448. result = info.st_size;
  449. }
  450. #endif
  451. return result;
  452. }
  453. String& string_toStreamIndented(String& target, const EntryType& source, const ReadableString& indentation) {
  454. string_append(target, indentation);
  455. if (source == EntryType::NotFound) {
  456. string_append(target, U"not found");
  457. } else if (source == EntryType::File) {
  458. string_append(target, U"a file");
  459. } else if (source == EntryType::Folder) {
  460. string_append(target, U"a folder");
  461. } else if (source == EntryType::SymbolicLink) {
  462. string_append(target, U"a symbolic link");
  463. } else {
  464. string_append(target, U"unhandled");
  465. }
  466. return target;
  467. }
  468. EntryType file_getEntryType(const ReadableString &path) {
  469. EntryType result = EntryType::NotFound;
  470. String optimizedPath = file_optimizePath(path, LOCAL_PATH_SYNTAX);
  471. Buffer buffer;
  472. const NativeChar *nativePath = toNativeString(optimizedPath, buffer);
  473. #ifdef USE_MICROSOFT_WINDOWS
  474. DWORD dwAttrib = GetFileAttributesW(nativePath);
  475. if (dwAttrib != INVALID_FILE_ATTRIBUTES) {
  476. if (dwAttrib & FILE_ATTRIBUTE_DIRECTORY) {
  477. result = EntryType::Folder;
  478. } else {
  479. result = EntryType::File;
  480. }
  481. }
  482. #else
  483. struct stat info;
  484. int errorCode = stat(nativePath, &info);
  485. if (errorCode == 0) {
  486. if (S_ISDIR(info.st_mode)) {
  487. result = EntryType::Folder;
  488. } else if (S_ISREG(info.st_mode)) {
  489. result = EntryType::File;
  490. } else if (S_ISLNK(info.st_mode)) {
  491. result = EntryType::SymbolicLink;
  492. } else {
  493. result = EntryType::UnhandledType;
  494. }
  495. }
  496. #endif
  497. return result;
  498. }
  499. bool file_getFolderContent(const ReadableString& folderPath, std::function<void(const ReadableString& entryPath, const ReadableString& entryName, EntryType entryType)> action) {
  500. String optimizedPath = file_optimizePath(folderPath, LOCAL_PATH_SYNTAX);
  501. #ifdef USE_MICROSOFT_WINDOWS
  502. String pattern = file_combinePaths(optimizedPath, U"*.*", LOCAL_PATH_SYNTAX);
  503. Buffer buffer;
  504. const NativeChar *nativePattern = toNativeString(pattern, buffer);
  505. WIN32_FIND_DATAW findData;
  506. HANDLE findHandle = FindFirstFileW(nativePattern, &findData);
  507. if (findHandle == INVALID_HANDLE_VALUE) {
  508. return false;
  509. } else {
  510. while (true) {
  511. String entryName = fromNativeString(findData.cFileName);
  512. if (!string_match(entryName, U".") && !string_match(entryName, U"..")) {
  513. String entryPath = file_combinePaths(optimizedPath, entryName, LOCAL_PATH_SYNTAX);
  514. EntryType entryType = EntryType::UnhandledType;
  515. if(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  516. entryType = EntryType::Folder;
  517. } else {
  518. entryType = EntryType::File;
  519. }
  520. action(entryPath, entryName, entryType);
  521. }
  522. if (!FindNextFileW(findHandle, &findData)) { break; }
  523. }
  524. FindClose(findHandle);
  525. }
  526. #else
  527. Buffer buffer;
  528. const NativeChar *nativePath = toNativeString(optimizedPath, buffer);
  529. DIR *directory = opendir(nativePath);
  530. if (directory == nullptr) {
  531. return false;
  532. } else {
  533. while (true) {
  534. dirent *entry = readdir(directory);
  535. if (entry != nullptr) {
  536. String entryName = fromNativeString(entry->d_name);
  537. if (!string_match(entryName, U".") && !string_match(entryName, U"..")) {
  538. String entryPath = file_combinePaths(optimizedPath, entryName, LOCAL_PATH_SYNTAX);
  539. EntryType entryType = file_getEntryType(entryPath);
  540. action(entryPath, entryName, entryType);
  541. }
  542. } else {
  543. break;
  544. }
  545. }
  546. }
  547. closedir(directory);
  548. #endif
  549. return true;
  550. }
  551. }