juce_File.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. File::File (const String& fullPathName)
  20. : fullPath (parseAbsolutePath (fullPathName))
  21. {
  22. }
  23. File File::createFileWithoutCheckingPath (const String& path) noexcept
  24. {
  25. File f;
  26. f.fullPath = path;
  27. return f;
  28. }
  29. File::File (const File& other)
  30. : fullPath (other.fullPath)
  31. {
  32. }
  33. File& File::operator= (const String& newPath)
  34. {
  35. fullPath = parseAbsolutePath (newPath);
  36. return *this;
  37. }
  38. File& File::operator= (const File& other)
  39. {
  40. fullPath = other.fullPath;
  41. return *this;
  42. }
  43. File::File (File&& other) noexcept
  44. : fullPath (std::move (other.fullPath))
  45. {
  46. }
  47. File& File::operator= (File&& other) noexcept
  48. {
  49. fullPath = std::move (other.fullPath);
  50. return *this;
  51. }
  52. JUCE_DECLARE_DEPRECATED_STATIC (const File File::nonexistent{};)
  53. //==============================================================================
  54. static String removeEllipsis (const String& path)
  55. {
  56. // This will quickly find both /../ and /./ at the expense of a minor
  57. // false-positive performance hit when path elements end in a dot.
  58. #if JUCE_WINDOWS
  59. if (path.contains (".\\"))
  60. #else
  61. if (path.contains ("./"))
  62. #endif
  63. {
  64. StringArray toks;
  65. toks.addTokens (path, File::getSeparatorString(), {});
  66. bool anythingChanged = false;
  67. for (int i = 1; i < toks.size(); ++i)
  68. {
  69. auto& t = toks[i];
  70. if (t == ".." && toks[i - 1] != "..")
  71. {
  72. anythingChanged = true;
  73. toks.removeRange (i - 1, 2);
  74. i = jmax (0, i - 2);
  75. }
  76. else if (t == ".")
  77. {
  78. anythingChanged = true;
  79. toks.remove (i--);
  80. }
  81. }
  82. if (anythingChanged)
  83. return toks.joinIntoString (File::getSeparatorString());
  84. }
  85. return path;
  86. }
  87. static String normaliseSeparators (const String& path)
  88. {
  89. auto normalisedPath = path;
  90. String separator (File::getSeparatorString());
  91. String doubleSeparator (separator + separator);
  92. auto uncPath = normalisedPath.startsWith (doubleSeparator)
  93. && ! normalisedPath.fromFirstOccurrenceOf (doubleSeparator, false, false).startsWith (separator);
  94. if (uncPath)
  95. normalisedPath = normalisedPath.fromFirstOccurrenceOf (doubleSeparator, false, false);
  96. while (normalisedPath.contains (doubleSeparator))
  97. normalisedPath = normalisedPath.replace (doubleSeparator, separator);
  98. return uncPath ? doubleSeparator + normalisedPath
  99. : normalisedPath;
  100. }
  101. bool File::isRoot() const
  102. {
  103. return fullPath.isNotEmpty() && *this == getParentDirectory();
  104. }
  105. String File::parseAbsolutePath (const String& p)
  106. {
  107. if (p.isEmpty())
  108. return {};
  109. #if JUCE_WINDOWS
  110. // Windows..
  111. auto path = normaliseSeparators (removeEllipsis (p.replaceCharacter ('/', '\\')));
  112. if (path.startsWithChar (getSeparatorChar()))
  113. {
  114. if (path[1] != getSeparatorChar())
  115. {
  116. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  117. If you're trying to parse a string that may be either a relative path or an absolute path,
  118. you MUST provide a context against which the partial path can be evaluated - you can do
  119. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  120. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  121. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  122. */
  123. jassertfalse;
  124. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  125. }
  126. }
  127. else if (! path.containsChar (':'))
  128. {
  129. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  130. If you're trying to parse a string that may be either a relative path or an absolute path,
  131. you MUST provide a context against which the partial path can be evaluated - you can do
  132. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  133. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  134. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  135. */
  136. jassertfalse;
  137. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  138. }
  139. #else
  140. // Mac or Linux..
  141. // Yes, I know it's legal for a unix pathname to contain a backslash, but this assertion is here
  142. // to catch anyone who's trying to run code that was written on Windows with hard-coded path names.
  143. // If that's why you've ended up here, use File::getChildFile() to build your paths instead.
  144. jassert ((! p.containsChar ('\\')) || (p.indexOfChar ('/') >= 0 && p.indexOfChar ('/') < p.indexOfChar ('\\')));
  145. auto path = normaliseSeparators (removeEllipsis (p));
  146. if (path.startsWithChar ('~'))
  147. {
  148. if (path[1] == getSeparatorChar() || path[1] == 0)
  149. {
  150. // expand a name of the form "~/abc"
  151. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  152. + path.substring (1);
  153. }
  154. else
  155. {
  156. // expand a name of type "~dave/abc"
  157. auto userName = path.substring (1).upToFirstOccurrenceOf ("/", false, false);
  158. if (auto* pw = getpwnam (userName.toUTF8()))
  159. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  160. }
  161. }
  162. else if (! path.startsWithChar (getSeparatorChar()))
  163. {
  164. #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS
  165. if (! (path.startsWith ("./") || path.startsWith ("../")))
  166. {
  167. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  168. If you're trying to parse a string that may be either a relative path or an absolute path,
  169. you MUST provide a context against which the partial path can be evaluated - you can do
  170. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  171. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  172. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  173. */
  174. jassertfalse;
  175. #if JUCE_LOG_ASSERTIONS
  176. Logger::writeToLog ("Illegal absolute path: " + path);
  177. #endif
  178. }
  179. #endif
  180. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  181. }
  182. #endif
  183. while (path.endsWithChar (getSeparatorChar()) && path != getSeparatorString()) // careful not to turn a single "/" into an empty string.
  184. path = path.dropLastCharacters (1);
  185. return path;
  186. }
  187. String File::addTrailingSeparator (const String& path)
  188. {
  189. return path.endsWithChar (getSeparatorChar()) ? path
  190. : path + getSeparatorChar();
  191. }
  192. //==============================================================================
  193. #if JUCE_LINUX
  194. #define NAMES_ARE_CASE_SENSITIVE 1
  195. #endif
  196. bool File::areFileNamesCaseSensitive()
  197. {
  198. #if NAMES_ARE_CASE_SENSITIVE
  199. return true;
  200. #else
  201. return false;
  202. #endif
  203. }
  204. static int compareFilenames (const String& name1, const String& name2) noexcept
  205. {
  206. #if NAMES_ARE_CASE_SENSITIVE
  207. return name1.compare (name2);
  208. #else
  209. return name1.compareIgnoreCase (name2);
  210. #endif
  211. }
  212. bool File::operator== (const File& other) const { return compareFilenames (fullPath, other.fullPath) == 0; }
  213. bool File::operator!= (const File& other) const { return compareFilenames (fullPath, other.fullPath) != 0; }
  214. bool File::operator< (const File& other) const { return compareFilenames (fullPath, other.fullPath) < 0; }
  215. bool File::operator> (const File& other) const { return compareFilenames (fullPath, other.fullPath) > 0; }
  216. //==============================================================================
  217. bool File::setReadOnly (const bool shouldBeReadOnly,
  218. const bool applyRecursively) const
  219. {
  220. bool worked = true;
  221. if (applyRecursively && isDirectory())
  222. for (auto& f : findChildFiles (File::findFilesAndDirectories, false))
  223. worked = f.setReadOnly (shouldBeReadOnly, true) && worked;
  224. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  225. }
  226. bool File::setExecutePermission (bool shouldBeExecutable) const
  227. {
  228. return setFileExecutableInternal (shouldBeExecutable);
  229. }
  230. bool File::deleteRecursively (bool followSymlinks) const
  231. {
  232. bool worked = true;
  233. if (isDirectory() && (followSymlinks || ! isSymbolicLink()))
  234. for (auto& f : findChildFiles (File::findFilesAndDirectories, false))
  235. worked = f.deleteRecursively (followSymlinks) && worked;
  236. return deleteFile() && worked;
  237. }
  238. bool File::moveFileTo (const File& newFile) const
  239. {
  240. if (newFile.fullPath == fullPath)
  241. return true;
  242. if (! exists())
  243. return false;
  244. #if ! NAMES_ARE_CASE_SENSITIVE
  245. if (*this != newFile)
  246. #endif
  247. if (! newFile.deleteFile())
  248. return false;
  249. return moveInternal (newFile);
  250. }
  251. bool File::copyFileTo (const File& newFile) const
  252. {
  253. return (*this == newFile)
  254. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  255. }
  256. bool File::replaceFileIn (const File& newFile) const
  257. {
  258. if (newFile.fullPath == fullPath)
  259. return true;
  260. if (! newFile.exists())
  261. return moveFileTo (newFile);
  262. if (! replaceInternal (newFile))
  263. return false;
  264. deleteFile();
  265. return true;
  266. }
  267. bool File::copyDirectoryTo (const File& newDirectory) const
  268. {
  269. if (isDirectory() && newDirectory.createDirectory())
  270. {
  271. for (auto& f : findChildFiles (File::findFiles, false))
  272. if (! f.copyFileTo (newDirectory.getChildFile (f.getFileName())))
  273. return false;
  274. for (auto& f : findChildFiles (File::findDirectories, false))
  275. if (! f.copyDirectoryTo (newDirectory.getChildFile (f.getFileName())))
  276. return false;
  277. return true;
  278. }
  279. return false;
  280. }
  281. //==============================================================================
  282. String File::getPathUpToLastSlash() const
  283. {
  284. auto lastSlash = fullPath.lastIndexOfChar (getSeparatorChar());
  285. if (lastSlash > 0)
  286. return fullPath.substring (0, lastSlash);
  287. if (lastSlash == 0)
  288. return getSeparatorString();
  289. return fullPath;
  290. }
  291. File File::getParentDirectory() const
  292. {
  293. return createFileWithoutCheckingPath (getPathUpToLastSlash());
  294. }
  295. //==============================================================================
  296. String File::getFileName() const
  297. {
  298. return fullPath.substring (fullPath.lastIndexOfChar (getSeparatorChar()) + 1);
  299. }
  300. String File::getFileNameWithoutExtension() const
  301. {
  302. auto lastSlash = fullPath.lastIndexOfChar (getSeparatorChar()) + 1;
  303. auto lastDot = fullPath.lastIndexOfChar ('.');
  304. if (lastDot > lastSlash)
  305. return fullPath.substring (lastSlash, lastDot);
  306. return fullPath.substring (lastSlash);
  307. }
  308. bool File::isAChildOf (const File& potentialParent) const
  309. {
  310. if (potentialParent.fullPath.isEmpty())
  311. return false;
  312. auto ourPath = getPathUpToLastSlash();
  313. if (compareFilenames (potentialParent.fullPath, ourPath) == 0)
  314. return true;
  315. if (potentialParent.fullPath.length() >= ourPath.length())
  316. return false;
  317. return getParentDirectory().isAChildOf (potentialParent);
  318. }
  319. int File::hashCode() const { return fullPath.hashCode(); }
  320. int64 File::hashCode64() const { return fullPath.hashCode64(); }
  321. //==============================================================================
  322. bool File::isAbsolutePath (StringRef path)
  323. {
  324. auto firstChar = *(path.text);
  325. return firstChar == getSeparatorChar()
  326. #if JUCE_WINDOWS
  327. || (firstChar != 0 && path.text[1] == ':');
  328. #else
  329. || firstChar == '~';
  330. #endif
  331. }
  332. File File::getChildFile (StringRef relativePath) const
  333. {
  334. auto r = relativePath.text;
  335. if (isAbsolutePath (r))
  336. return File (String (r));
  337. #if JUCE_WINDOWS
  338. if (r.indexOf ((juce_wchar) '/') >= 0)
  339. return getChildFile (String (r).replaceCharacter ('/', '\\'));
  340. #endif
  341. auto path = fullPath;
  342. auto separatorChar = getSeparatorChar();
  343. while (*r == '.')
  344. {
  345. auto lastPos = r;
  346. auto secondChar = *++r;
  347. if (secondChar == '.') // remove "../"
  348. {
  349. auto thirdChar = *++r;
  350. if (thirdChar == separatorChar || thirdChar == 0)
  351. {
  352. auto lastSlash = path.lastIndexOfChar (separatorChar);
  353. if (lastSlash >= 0)
  354. path = path.substring (0, lastSlash);
  355. while (*r == separatorChar) // ignore duplicate slashes
  356. ++r;
  357. }
  358. else
  359. {
  360. r = lastPos;
  361. break;
  362. }
  363. }
  364. else if (secondChar == separatorChar || secondChar == 0) // remove "./"
  365. {
  366. while (*r == separatorChar) // ignore duplicate slashes
  367. ++r;
  368. }
  369. else
  370. {
  371. r = lastPos;
  372. break;
  373. }
  374. }
  375. path = addTrailingSeparator (path);
  376. path.appendCharPointer (r);
  377. return File (path);
  378. }
  379. File File::getSiblingFile (StringRef fileName) const
  380. {
  381. return getParentDirectory().getChildFile (fileName);
  382. }
  383. //==============================================================================
  384. String File::descriptionOfSizeInBytes (const int64 bytes)
  385. {
  386. const char* suffix;
  387. double divisor = 0;
  388. if (bytes == 1) { suffix = " byte"; }
  389. else if (bytes < 1024) { suffix = " bytes"; }
  390. else if (bytes < 1024 * 1024) { suffix = " KB"; divisor = 1024.0; }
  391. else if (bytes < 1024 * 1024 * 1024) { suffix = " MB"; divisor = 1024.0 * 1024.0; }
  392. else { suffix = " GB"; divisor = 1024.0 * 1024.0 * 1024.0; }
  393. return (divisor > 0 ? String (bytes / divisor, 1) : String (bytes)) + suffix;
  394. }
  395. //==============================================================================
  396. Result File::create() const
  397. {
  398. if (exists())
  399. return Result::ok();
  400. auto parentDir = getParentDirectory();
  401. if (parentDir == *this)
  402. return Result::fail ("Cannot create parent directory");
  403. auto r = parentDir.createDirectory();
  404. if (r.wasOk())
  405. {
  406. FileOutputStream fo (*this, 8);
  407. r = fo.getStatus();
  408. }
  409. return r;
  410. }
  411. Result File::createDirectory() const
  412. {
  413. if (isDirectory())
  414. return Result::ok();
  415. auto parentDir = getParentDirectory();
  416. if (parentDir == *this)
  417. return Result::fail ("Cannot create parent directory");
  418. auto r = parentDir.createDirectory();
  419. if (r.wasOk())
  420. r = createDirectoryInternal (fullPath.trimCharactersAtEnd (getSeparatorString()));
  421. return r;
  422. }
  423. //==============================================================================
  424. Time File::getLastModificationTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (m); }
  425. Time File::getLastAccessTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (a); }
  426. Time File::getCreationTime() const { int64 m, a, c; getFileTimesInternal (m, a, c); return Time (c); }
  427. bool File::setLastModificationTime (Time t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  428. bool File::setLastAccessTime (Time t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  429. bool File::setCreationTime (Time t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  430. //==============================================================================
  431. bool File::loadFileAsData (MemoryBlock& destBlock) const
  432. {
  433. if (! existsAsFile())
  434. return false;
  435. FileInputStream in (*this);
  436. return in.openedOk() && getSize() == (int64) in.readIntoMemoryBlock (destBlock);
  437. }
  438. String File::loadFileAsString() const
  439. {
  440. if (! existsAsFile())
  441. return {};
  442. FileInputStream in (*this);
  443. return in.openedOk() ? in.readEntireStreamAsString()
  444. : String();
  445. }
  446. void File::readLines (StringArray& destLines) const
  447. {
  448. destLines.addLines (loadFileAsString());
  449. }
  450. //==============================================================================
  451. Array<File> File::findChildFiles (int whatToLookFor, bool searchRecursively, const String& wildcard) const
  452. {
  453. Array<File> results;
  454. findChildFiles (results, whatToLookFor, searchRecursively, wildcard);
  455. return results;
  456. }
  457. int File::findChildFiles (Array<File>& results, int whatToLookFor, bool searchRecursively, const String& wildcard) const
  458. {
  459. int total = 0;
  460. for (DirectoryIterator di (*this, searchRecursively, wildcard, whatToLookFor); di.next();)
  461. {
  462. results.add (di.getFile());
  463. ++total;
  464. }
  465. return total;
  466. }
  467. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  468. {
  469. int total = 0;
  470. for (DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor); di.next();)
  471. ++total;
  472. return total;
  473. }
  474. bool File::containsSubDirectories() const
  475. {
  476. if (! isDirectory())
  477. return false;
  478. DirectoryIterator di (*this, false, "*", findDirectories);
  479. return di.next();
  480. }
  481. //==============================================================================
  482. File File::getNonexistentChildFile (const String& suggestedPrefix,
  483. const String& suffix,
  484. bool putNumbersInBrackets) const
  485. {
  486. auto f = getChildFile (suggestedPrefix + suffix);
  487. if (f.exists())
  488. {
  489. int number = 1;
  490. auto prefix = suggestedPrefix;
  491. // remove any bracketed numbers that may already be on the end..
  492. if (prefix.trim().endsWithChar (')'))
  493. {
  494. putNumbersInBrackets = true;
  495. auto openBracks = prefix.lastIndexOfChar ('(');
  496. auto closeBracks = prefix.lastIndexOfChar (')');
  497. if (openBracks > 0
  498. && closeBracks > openBracks
  499. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  500. {
  501. number = prefix.substring (openBracks + 1, closeBracks).getIntValue();
  502. prefix = prefix.substring (0, openBracks);
  503. }
  504. }
  505. do
  506. {
  507. auto newName = prefix;
  508. if (putNumbersInBrackets)
  509. {
  510. newName << '(' << ++number << ')';
  511. }
  512. else
  513. {
  514. if (CharacterFunctions::isDigit (prefix.getLastCharacter()))
  515. newName << '_'; // pad with an underscore if the name already ends in a digit
  516. newName << ++number;
  517. }
  518. f = getChildFile (newName + suffix);
  519. } while (f.exists());
  520. }
  521. return f;
  522. }
  523. File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  524. {
  525. if (! exists())
  526. return *this;
  527. return getParentDirectory().getNonexistentChildFile (getFileNameWithoutExtension(),
  528. getFileExtension(),
  529. putNumbersInBrackets);
  530. }
  531. //==============================================================================
  532. String File::getFileExtension() const
  533. {
  534. auto indexOfDot = fullPath.lastIndexOfChar ('.');
  535. if (indexOfDot > fullPath.lastIndexOfChar (getSeparatorChar()))
  536. return fullPath.substring (indexOfDot);
  537. return {};
  538. }
  539. bool File::hasFileExtension (StringRef possibleSuffix) const
  540. {
  541. if (possibleSuffix.isEmpty())
  542. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (getSeparatorChar());
  543. auto semicolon = possibleSuffix.text.indexOf ((juce_wchar) ';');
  544. if (semicolon >= 0)
  545. return hasFileExtension (String (possibleSuffix.text).substring (0, semicolon).trimEnd())
  546. || hasFileExtension ((possibleSuffix.text + (semicolon + 1)).findEndOfWhitespace());
  547. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  548. {
  549. if (possibleSuffix.text[0] == '.')
  550. return true;
  551. auto dotPos = fullPath.length() - possibleSuffix.length() - 1;
  552. if (dotPos >= 0)
  553. return fullPath[dotPos] == '.';
  554. }
  555. return false;
  556. }
  557. File File::withFileExtension (StringRef newExtension) const
  558. {
  559. if (fullPath.isEmpty())
  560. return {};
  561. auto filePart = getFileName();
  562. auto lastDot = filePart.lastIndexOfChar ('.');
  563. if (lastDot >= 0)
  564. filePart = filePart.substring (0, lastDot);
  565. if (newExtension.isNotEmpty() && newExtension.text[0] != '.')
  566. filePart << '.';
  567. return getSiblingFile (filePart + newExtension);
  568. }
  569. //==============================================================================
  570. bool File::startAsProcess (const String& parameters) const
  571. {
  572. return exists() && Process::openDocument (fullPath, parameters);
  573. }
  574. //==============================================================================
  575. FileInputStream* File::createInputStream() const
  576. {
  577. std::unique_ptr<FileInputStream> fin (new FileInputStream (*this));
  578. if (fin->openedOk())
  579. return fin.release();
  580. return nullptr;
  581. }
  582. FileOutputStream* File::createOutputStream (size_t bufferSize) const
  583. {
  584. std::unique_ptr<FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  585. return out->failedToOpen() ? nullptr
  586. : out.release();
  587. }
  588. //==============================================================================
  589. bool File::appendData (const void* const dataToAppend,
  590. const size_t numberOfBytes) const
  591. {
  592. jassert (((ssize_t) numberOfBytes) >= 0);
  593. if (numberOfBytes == 0)
  594. return true;
  595. FileOutputStream out (*this, 8192);
  596. return out.openedOk() && out.write (dataToAppend, numberOfBytes);
  597. }
  598. bool File::replaceWithData (const void* const dataToWrite,
  599. const size_t numberOfBytes) const
  600. {
  601. if (numberOfBytes == 0)
  602. return deleteFile();
  603. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  604. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  605. return tempFile.overwriteTargetFileWithTemporary();
  606. }
  607. bool File::appendText (const String& text, bool asUnicode, bool writeHeaderBytes, const char* lineFeed) const
  608. {
  609. FileOutputStream out (*this);
  610. if (out.failedToOpen())
  611. return false;
  612. return out.writeText (text, asUnicode, writeHeaderBytes, lineFeed);
  613. }
  614. bool File::replaceWithText (const String& textToWrite, bool asUnicode, bool writeHeaderBytes, const char* lineFeed) const
  615. {
  616. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  617. tempFile.getFile().appendText (textToWrite, asUnicode, writeHeaderBytes, lineFeed);
  618. return tempFile.overwriteTargetFileWithTemporary();
  619. }
  620. bool File::hasIdenticalContentTo (const File& other) const
  621. {
  622. if (other == *this)
  623. return true;
  624. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  625. {
  626. FileInputStream in1 (*this), in2 (other);
  627. if (in1.openedOk() && in2.openedOk())
  628. {
  629. const int bufferSize = 4096;
  630. HeapBlock<char> buffer1 (bufferSize), buffer2 (bufferSize);
  631. for (;;)
  632. {
  633. auto num1 = in1.read (buffer1, bufferSize);
  634. auto num2 = in2.read (buffer2, bufferSize);
  635. if (num1 != num2)
  636. break;
  637. if (num1 <= 0)
  638. return true;
  639. if (memcmp (buffer1, buffer2, (size_t) num1) != 0)
  640. break;
  641. }
  642. }
  643. }
  644. return false;
  645. }
  646. //==============================================================================
  647. String File::createLegalPathName (const String& original)
  648. {
  649. auto s = original;
  650. String start;
  651. if (s.isNotEmpty() && s[1] == ':')
  652. {
  653. start = s.substring (0, 2);
  654. s = s.substring (2);
  655. }
  656. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  657. .substring (0, 1024);
  658. }
  659. String File::createLegalFileName (const String& original)
  660. {
  661. auto s = original.removeCharacters ("\"#@,;:<>*^|?\\/");
  662. const int maxLength = 128; // only the length of the filename, not the whole path
  663. auto len = s.length();
  664. if (len > maxLength)
  665. {
  666. auto lastDot = s.lastIndexOfChar ('.');
  667. if (lastDot > jmax (0, len - 12))
  668. {
  669. s = s.substring (0, maxLength - (len - lastDot))
  670. + s.substring (lastDot);
  671. }
  672. else
  673. {
  674. s = s.substring (0, maxLength);
  675. }
  676. }
  677. return s;
  678. }
  679. //==============================================================================
  680. static int countNumberOfSeparators (String::CharPointerType s)
  681. {
  682. int num = 0;
  683. for (;;)
  684. {
  685. auto c = s.getAndAdvance();
  686. if (c == 0)
  687. break;
  688. if (c == File::getSeparatorChar())
  689. ++num;
  690. }
  691. return num;
  692. }
  693. String File::getRelativePathFrom (const File& dir) const
  694. {
  695. if (dir == *this)
  696. return ".";
  697. auto thisPath = fullPath;
  698. while (thisPath.endsWithChar (getSeparatorChar()))
  699. thisPath = thisPath.dropLastCharacters (1);
  700. auto dirPath = addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  701. : dir.fullPath);
  702. int commonBitLength = 0;
  703. auto thisPathAfterCommon = thisPath.getCharPointer();
  704. auto dirPathAfterCommon = dirPath.getCharPointer();
  705. {
  706. auto thisPathIter = thisPath.getCharPointer();
  707. auto dirPathIter = dirPath.getCharPointer();
  708. for (int i = 0;;)
  709. {
  710. auto c1 = thisPathIter.getAndAdvance();
  711. auto c2 = dirPathIter.getAndAdvance();
  712. #if NAMES_ARE_CASE_SENSITIVE
  713. if (c1 != c2
  714. #else
  715. if ((c1 != c2 && CharacterFunctions::toLowerCase (c1) != CharacterFunctions::toLowerCase (c2))
  716. #endif
  717. || c1 == 0)
  718. break;
  719. ++i;
  720. if (c1 == getSeparatorChar())
  721. {
  722. thisPathAfterCommon = thisPathIter;
  723. dirPathAfterCommon = dirPathIter;
  724. commonBitLength = i;
  725. }
  726. }
  727. }
  728. // if the only common bit is the root, then just return the full path..
  729. if (commonBitLength == 0 || (commonBitLength == 1 && thisPath[1] == getSeparatorChar()))
  730. return fullPath;
  731. auto numUpDirectoriesNeeded = countNumberOfSeparators (dirPathAfterCommon);
  732. if (numUpDirectoriesNeeded == 0)
  733. return thisPathAfterCommon;
  734. #if JUCE_WINDOWS
  735. auto s = String::repeatedString ("..\\", numUpDirectoriesNeeded);
  736. #else
  737. auto s = String::repeatedString ("../", numUpDirectoriesNeeded);
  738. #endif
  739. s.appendCharPointer (thisPathAfterCommon);
  740. return s;
  741. }
  742. //==============================================================================
  743. File File::createTempFile (StringRef fileNameEnding)
  744. {
  745. auto tempFile = getSpecialLocation (tempDirectory)
  746. .getChildFile ("temp_" + String::toHexString (Random::getSystemRandom().nextInt()))
  747. .withFileExtension (fileNameEnding);
  748. if (tempFile.exists())
  749. return createTempFile (fileNameEnding);
  750. return tempFile;
  751. }
  752. bool File::createSymbolicLink (const File& linkFileToCreate,
  753. const String& nativePathOfTarget,
  754. bool overwriteExisting)
  755. {
  756. if (linkFileToCreate.exists())
  757. {
  758. if (! linkFileToCreate.isSymbolicLink())
  759. {
  760. // user has specified an existing file / directory as the link
  761. // this is bad! the user could end up unintentionally destroying data
  762. jassertfalse;
  763. return false;
  764. }
  765. if (overwriteExisting)
  766. linkFileToCreate.deleteFile();
  767. }
  768. #if JUCE_MAC || JUCE_LINUX
  769. // one common reason for getting an error here is that the file already exists
  770. if (symlink (nativePathOfTarget.toRawUTF8(), linkFileToCreate.getFullPathName().toRawUTF8()) == -1)
  771. {
  772. jassertfalse;
  773. return false;
  774. }
  775. return true;
  776. #elif JUCE_MSVC
  777. File targetFile (linkFileToCreate.getSiblingFile (nativePathOfTarget));
  778. return CreateSymbolicLink (linkFileToCreate.getFullPathName().toWideCharPointer(),
  779. nativePathOfTarget.toWideCharPointer(),
  780. targetFile.isDirectory() ? SYMBOLIC_LINK_FLAG_DIRECTORY : 0) != FALSE;
  781. #else
  782. ignoreUnused (nativePathOfTarget);
  783. jassertfalse; // symbolic links not supported on this platform!
  784. return false;
  785. #endif
  786. }
  787. bool File::createSymbolicLink (const File& linkFileToCreate, bool overwriteExisting) const
  788. {
  789. return createSymbolicLink (linkFileToCreate, getFullPathName(), overwriteExisting);
  790. }
  791. #if ! JUCE_WINDOWS
  792. File File::getLinkedTarget() const
  793. {
  794. if (isSymbolicLink())
  795. return getSiblingFile (getNativeLinkedTarget());
  796. return *this;
  797. }
  798. #endif
  799. //==============================================================================
  800. MemoryMappedFile::MemoryMappedFile (const File& file, MemoryMappedFile::AccessMode mode, bool exclusive)
  801. : range (0, file.getSize())
  802. {
  803. openInternal (file, mode, exclusive);
  804. }
  805. MemoryMappedFile::MemoryMappedFile (const File& file, const Range<int64>& fileRange, AccessMode mode, bool exclusive)
  806. : range (fileRange.getIntersectionWith (Range<int64> (0, file.getSize())))
  807. {
  808. openInternal (file, mode, exclusive);
  809. }
  810. //==============================================================================
  811. //==============================================================================
  812. #if JUCE_UNIT_TESTS
  813. class FileTests : public UnitTest
  814. {
  815. public:
  816. FileTests()
  817. : UnitTest ("Files", UnitTestCategories::files)
  818. {}
  819. void runTest() override
  820. {
  821. beginTest ("Reading");
  822. const File home (File::getSpecialLocation (File::userHomeDirectory));
  823. const File temp (File::getSpecialLocation (File::tempDirectory));
  824. expect (! File().exists());
  825. expect (! File().existsAsFile());
  826. expect (! File().isDirectory());
  827. #if ! JUCE_WINDOWS
  828. expect (File("/").isDirectory());
  829. #endif
  830. expect (home.isDirectory());
  831. expect (home.exists());
  832. expect (! home.existsAsFile());
  833. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  834. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  835. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  836. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  837. expect (home.getVolumeTotalSize() > 1024 * 1024);
  838. expect (home.getBytesFreeOnVolume() > 0);
  839. expect (! home.isHidden());
  840. expect (home.isOnHardDisk());
  841. expect (! home.isOnCDRomDrive());
  842. expect (File::getCurrentWorkingDirectory().exists());
  843. expect (home.setAsCurrentWorkingDirectory());
  844. expect (File::getCurrentWorkingDirectory() == home);
  845. {
  846. Array<File> roots;
  847. File::findFileSystemRoots (roots);
  848. expect (roots.size() > 0);
  849. int numRootsExisting = 0;
  850. for (int i = 0; i < roots.size(); ++i)
  851. if (roots[i].exists())
  852. ++numRootsExisting;
  853. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  854. expect (numRootsExisting > 0);
  855. }
  856. beginTest ("Writing");
  857. File demoFolder (temp.getChildFile ("JUCE UnitTests Temp Folder.folder"));
  858. expect (demoFolder.deleteRecursively());
  859. expect (demoFolder.createDirectory());
  860. expect (demoFolder.isDirectory());
  861. expect (demoFolder.getParentDirectory() == temp);
  862. expect (temp.isDirectory());
  863. expect (temp.findChildFiles (File::findFilesAndDirectories, false, "*").contains (demoFolder));
  864. expect (temp.findChildFiles (File::findDirectories, true, "*.folder").contains (demoFolder));
  865. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  866. expect (tempFile.getFileExtension() == ".txt");
  867. expect (tempFile.hasFileExtension (".txt"));
  868. expect (tempFile.hasFileExtension ("txt"));
  869. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  870. expect (tempFile.withFileExtension ("xyz").hasFileExtension ("abc;xyz;foo"));
  871. expect (tempFile.withFileExtension ("xyz").hasFileExtension ("xyz;foo"));
  872. expect (! tempFile.withFileExtension ("h").hasFileExtension ("bar;foo;xx"));
  873. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  874. expect (tempFile.hasWriteAccess());
  875. expect (home.getChildFile (".") == home);
  876. expect (home.getChildFile ("..") == home.getParentDirectory());
  877. expect (home.getChildFile (".xyz").getFileName() == ".xyz");
  878. expect (home.getChildFile ("..xyz").getFileName() == "..xyz");
  879. expect (home.getChildFile ("...xyz").getFileName() == "...xyz");
  880. expect (home.getChildFile ("./xyz") == home.getChildFile ("xyz"));
  881. expect (home.getChildFile ("././xyz") == home.getChildFile ("xyz"));
  882. expect (home.getChildFile ("../xyz") == home.getParentDirectory().getChildFile ("xyz"));
  883. expect (home.getChildFile (".././xyz") == home.getParentDirectory().getChildFile ("xyz"));
  884. expect (home.getChildFile (".././xyz/./abc") == home.getParentDirectory().getChildFile ("xyz/abc"));
  885. expect (home.getChildFile ("./../xyz") == home.getParentDirectory().getChildFile ("xyz"));
  886. expect (home.getChildFile ("a1/a2/a3/./../../a4") == home.getChildFile ("a1/a4"));
  887. {
  888. FileOutputStream fo (tempFile);
  889. fo.write ("0123456789", 10);
  890. }
  891. expect (tempFile.exists());
  892. expect (tempFile.getSize() == 10);
  893. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  894. expectEquals (tempFile.loadFileAsString(), String ("0123456789"));
  895. expect (! demoFolder.containsSubDirectories());
  896. expectEquals (tempFile.getRelativePathFrom (demoFolder.getParentDirectory()), demoFolder.getFileName() + File::getSeparatorString() + tempFile.getFileName());
  897. expectEquals (demoFolder.getParentDirectory().getRelativePathFrom (tempFile), ".." + File::getSeparatorString() + ".." + File::getSeparatorString() + demoFolder.getParentDirectory().getFileName());
  898. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  899. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  900. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  901. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  902. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  903. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  904. expect (demoFolder.containsSubDirectories());
  905. expect (tempFile.hasWriteAccess());
  906. tempFile.setReadOnly (true);
  907. expect (! tempFile.hasWriteAccess());
  908. tempFile.setReadOnly (false);
  909. expect (tempFile.hasWriteAccess());
  910. Time t (Time::getCurrentTime());
  911. tempFile.setLastModificationTime (t);
  912. Time t2 = tempFile.getLastModificationTime();
  913. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  914. {
  915. MemoryBlock mb;
  916. tempFile.loadFileAsData (mb);
  917. expect (mb.getSize() == 10);
  918. expect (mb[0] == '0');
  919. }
  920. {
  921. expect (tempFile.getSize() == 10);
  922. FileOutputStream fo (tempFile);
  923. expect (fo.openedOk());
  924. expect (fo.setPosition (7));
  925. expect (fo.truncate().wasOk());
  926. expect (tempFile.getSize() == 7);
  927. fo.write ("789", 3);
  928. fo.flush();
  929. expect (tempFile.getSize() == 10);
  930. }
  931. beginTest ("Memory-mapped files");
  932. {
  933. MemoryMappedFile mmf (tempFile, MemoryMappedFile::readOnly);
  934. expect (mmf.getSize() == 10);
  935. expect (mmf.getData() != nullptr);
  936. expect (memcmp (mmf.getData(), "0123456789", 10) == 0);
  937. }
  938. {
  939. const File tempFile2 (tempFile.getNonexistentSibling (false));
  940. expect (tempFile2.create());
  941. expect (tempFile2.appendData ("xxxxxxxxxx", 10));
  942. {
  943. MemoryMappedFile mmf (tempFile2, MemoryMappedFile::readWrite);
  944. expect (mmf.getSize() == 10);
  945. expect (mmf.getData() != nullptr);
  946. memcpy (mmf.getData(), "abcdefghij", 10);
  947. }
  948. {
  949. MemoryMappedFile mmf (tempFile2, MemoryMappedFile::readWrite);
  950. expect (mmf.getSize() == 10);
  951. expect (mmf.getData() != nullptr);
  952. expect (memcmp (mmf.getData(), "abcdefghij", 10) == 0);
  953. }
  954. expect (tempFile2.deleteFile());
  955. }
  956. beginTest ("More writing");
  957. expect (tempFile.appendData ("abcdefghij", 10));
  958. expect (tempFile.getSize() == 20);
  959. expect (tempFile.replaceWithData ("abcdefghij", 10));
  960. expect (tempFile.getSize() == 10);
  961. File tempFile2 (tempFile.getNonexistentSibling (false));
  962. expect (tempFile.copyFileTo (tempFile2));
  963. expect (tempFile2.exists());
  964. expect (tempFile2.hasIdenticalContentTo (tempFile));
  965. expect (tempFile.deleteFile());
  966. expect (! tempFile.exists());
  967. expect (tempFile2.moveFileTo (tempFile));
  968. expect (tempFile.exists());
  969. expect (! tempFile2.exists());
  970. expect (demoFolder.deleteRecursively());
  971. expect (! demoFolder.exists());
  972. {
  973. URL url ("https://audio.dev/foo/bar/");
  974. expectEquals (url.toString (false), String ("https://audio.dev/foo/bar/"));
  975. expectEquals (url.getChildURL ("x").toString (false), String ("https://audio.dev/foo/bar/x"));
  976. expectEquals (url.getParentURL().toString (false), String ("https://audio.dev/foo"));
  977. expectEquals (url.getParentURL().getParentURL().toString (false), String ("https://audio.dev/"));
  978. expectEquals (url.getParentURL().getParentURL().getParentURL().toString (false), String ("https://audio.dev/"));
  979. expectEquals (url.getParentURL().getChildURL ("x").toString (false), String ("https://audio.dev/foo/x"));
  980. expectEquals (url.getParentURL().getParentURL().getParentURL().getChildURL ("x").toString (false), String ("https://audio.dev/x"));
  981. }
  982. {
  983. URL url ("https://audio.dev/foo/bar");
  984. expectEquals (url.toString (false), String ("https://audio.dev/foo/bar"));
  985. expectEquals (url.getChildURL ("x").toString (false), String ("https://audio.dev/foo/bar/x"));
  986. expectEquals (url.getParentURL().toString (false), String ("https://audio.dev/foo"));
  987. expectEquals (url.getParentURL().getParentURL().toString (false), String ("https://audio.dev/"));
  988. expectEquals (url.getParentURL().getParentURL().getParentURL().toString (false), String ("https://audio.dev/"));
  989. expectEquals (url.getParentURL().getChildURL ("x").toString (false), String ("https://audio.dev/foo/x"));
  990. expectEquals (url.getParentURL().getParentURL().getParentURL().getChildURL ("x").toString (false), String ("https://audio.dev/x"));
  991. }
  992. }
  993. };
  994. static FileTests fileUnitTests;
  995. #endif
  996. } // namespace juce