juce_File.cpp 39 KB

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