The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1125 lines
46KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  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. #if ! DOXYGEN && (JUCE_MAC || JUCE_IOS)
  18. #if __LP64__
  19. using OSType = unsigned int;
  20. #else
  21. using OSType = unsigned long;
  22. #endif
  23. #endif
  24. namespace juce
  25. {
  26. //==============================================================================
  27. /**
  28. Represents a local file or directory.
  29. This class encapsulates the absolute pathname of a file or directory, and
  30. has methods for finding out about the file and changing its properties.
  31. To read or write to the file, there are methods for returning an input or
  32. output stream.
  33. @see FileInputStream, FileOutputStream
  34. @tags{Core}
  35. */
  36. class JUCE_API File final
  37. {
  38. public:
  39. //==============================================================================
  40. /** Creates an (invalid) file object.
  41. The file is initially set to an empty path, so getFullPathName() will return
  42. an empty string.
  43. You can use its operator= method to point it at a proper file.
  44. */
  45. File() = default;
  46. /** Creates a file from an absolute path.
  47. If the path supplied is a relative path, it is taken to be relative
  48. to the current working directory (see File::getCurrentWorkingDirectory()),
  49. but this isn't a recommended way of creating a file, because you
  50. never know what the CWD is going to be.
  51. On the Mac/Linux, the path can include "~" notation for referring to
  52. user home directories.
  53. */
  54. File (const String& absolutePath);
  55. /** Creates a copy of another file object. */
  56. File (const File&);
  57. /** Destructor. */
  58. ~File() = default;
  59. /** Sets the file based on an absolute pathname.
  60. If the path supplied is a relative path, it is taken to be relative
  61. to the current working directory (see File::getCurrentWorkingDirectory()),
  62. but this isn't a recommended way of creating a file, because you
  63. never know what the CWD is going to be.
  64. On the Mac/Linux, the path can include "~" notation for referring to
  65. user home directories.
  66. */
  67. File& operator= (const String& newAbsolutePath);
  68. /** Copies from another file object. */
  69. File& operator= (const File& otherFile);
  70. /** Move constructor */
  71. File (File&&) noexcept;
  72. /** Move assignment operator */
  73. File& operator= (File&&) noexcept;
  74. //==============================================================================
  75. /** Checks whether the file actually exists.
  76. @returns true if the file exists, either as a file or a directory.
  77. @see existsAsFile, isDirectory
  78. */
  79. bool exists() const;
  80. /** Checks whether the file exists and is a file rather than a directory.
  81. @returns true only if this is a real file, false if it's a directory
  82. or doesn't exist
  83. @see exists, isDirectory
  84. */
  85. bool existsAsFile() const;
  86. /** Checks whether the file is a directory that exists.
  87. @returns true only if the file is a directory which actually exists, so
  88. false if it's a file or doesn't exist at all
  89. @see exists, existsAsFile
  90. */
  91. bool isDirectory() const;
  92. /** Checks whether the path of this file represents the root of a file system,
  93. irrespective of its existence.
  94. This will return true for "C:", "D:", etc on Windows and "/" on other
  95. platforms.
  96. */
  97. bool isRoot() const;
  98. /** Returns the size of the file in bytes.
  99. @returns the number of bytes in the file, or 0 if it doesn't exist.
  100. */
  101. int64 getSize() const;
  102. /** Utility function to convert a file size in bytes to a neat string description.
  103. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  104. 2000000 would produce "2 MB", etc.
  105. */
  106. static String descriptionOfSizeInBytes (int64 bytes);
  107. //==============================================================================
  108. /** Returns the complete, absolute path of this file.
  109. This includes the filename and all its parent folders. On Windows it'll
  110. also include the drive letter prefix; on Mac or Linux it'll be a complete
  111. path starting from the root folder.
  112. If you just want the file's name, you should use getFileName() or
  113. getFileNameWithoutExtension().
  114. @see getFileName, getRelativePathFrom
  115. */
  116. const String& getFullPathName() const noexcept { return fullPath; }
  117. /** Returns the last section of the pathname.
  118. Returns just the final part of the path - e.g. if the whole path
  119. is "/moose/fish/foo.txt" this will return "foo.txt".
  120. For a directory, it returns the final part of the path - e.g. for the
  121. directory "/moose/fish" it'll return "fish".
  122. If the filename begins with a dot, it'll return the whole filename, e.g. for
  123. "/moose/.fish", it'll return ".fish"
  124. @see getFullPathName, getFileNameWithoutExtension
  125. */
  126. String getFileName() const;
  127. /** Creates a relative path that refers to a file relatively to a given directory.
  128. e.g. File ("/moose/foo.txt").getRelativePathFrom (File ("/moose/fish/haddock"))
  129. would return "../../foo.txt".
  130. If it's not possible to navigate from one file to the other, an absolute
  131. path is returned. If the paths are invalid, an empty string may also be
  132. returned.
  133. @param directoryToBeRelativeTo the directory which the resultant string will
  134. be relative to. If this is actually a file rather than
  135. a directory, its parent directory will be used instead.
  136. If it doesn't exist, it's assumed to be a directory.
  137. @see getChildFile, isAbsolutePath
  138. */
  139. String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  140. //==============================================================================
  141. /** Returns the file's extension.
  142. Returns the file extension of this file, also including the dot.
  143. e.g. "/moose/fish/foo.txt" would return ".txt"
  144. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  145. */
  146. String getFileExtension() const;
  147. /** Checks whether the file has a given extension.
  148. @param extensionToTest the extension to look for - it doesn't matter whether or
  149. not this string has a dot at the start, so ".wav" and "wav"
  150. will have the same effect. To compare with multiple extensions, this
  151. parameter can contain multiple strings, separated by semi-colons -
  152. so, for example: hasFileExtension (".jpeg;png;gif") would return
  153. true if the file has any of those three extensions.
  154. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  155. */
  156. bool hasFileExtension (StringRef extensionToTest) const;
  157. /** Returns a version of this file with a different file extension.
  158. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  159. @param newExtension the new extension, either with or without a dot at the start (this
  160. doesn't make any difference). To get remove a file's extension altogether,
  161. pass an empty string into this function.
  162. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  163. */
  164. File withFileExtension (StringRef newExtension) const;
  165. /** Returns the last part of the filename, without its file extension.
  166. e.g. for "/moose/fish/foo.txt" this will return "foo".
  167. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  168. */
  169. String getFileNameWithoutExtension() const;
  170. //==============================================================================
  171. /** Returns a 32-bit hash-code that identifies this file.
  172. This is based on the filename. Obviously it's possible, although unlikely, that
  173. two files will have the same hash-code.
  174. */
  175. int hashCode() const;
  176. /** Returns a 64-bit hash-code that identifies this file.
  177. This is based on the filename. Obviously it's possible, although unlikely, that
  178. two files will have the same hash-code.
  179. */
  180. int64 hashCode64() const;
  181. //==============================================================================
  182. /** Returns a file that represents a relative (or absolute) sub-path of the current one.
  183. This will find a child file or directory of the current object.
  184. e.g.
  185. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  186. File ("/moose/fish").getChildFile ("haddock/foo.txt") will produce "/moose/fish/haddock/foo.txt".
  187. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  188. If the string is actually an absolute path, it will be treated as such, e.g.
  189. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  190. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  191. */
  192. File getChildFile (StringRef relativeOrAbsolutePath) const;
  193. /** Returns a file which is in the same directory as this one.
  194. This is equivalent to getParentDirectory().getChildFile (name).
  195. @see getChildFile, getParentDirectory
  196. */
  197. File getSiblingFile (StringRef siblingFileName) const;
  198. //==============================================================================
  199. /** Returns the directory that contains this file or directory.
  200. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  201. If you are already at the root directory ("/" or "C:") then this method will
  202. return the root directory.
  203. */
  204. File getParentDirectory() const;
  205. /** Checks whether a file is somewhere inside a directory.
  206. Returns true if this file is somewhere inside a subdirectory of the directory
  207. that is passed in. Neither file actually has to exist, because the function
  208. just checks the paths for similarities.
  209. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  210. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  211. */
  212. bool isAChildOf (const File& potentialParentDirectory) const;
  213. //==============================================================================
  214. /** Chooses a filename relative to this one that doesn't already exist.
  215. If this file is a directory, this will return a child file of this
  216. directory that doesn't exist, by adding numbers to a prefix and suffix until
  217. it finds one that isn't already there.
  218. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  219. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  220. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  221. @param prefix the string to use for the filename before the number
  222. @param suffix the string to add to the filename after the number
  223. @param putNumbersInBrackets if true, this will create filenames in the
  224. format "prefix(number)suffix", if false, it will leave the
  225. brackets out.
  226. */
  227. File getNonexistentChildFile (const String& prefix,
  228. const String& suffix,
  229. bool putNumbersInBrackets = true) const;
  230. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  231. If this file doesn't exist, this will just return itself, otherwise it
  232. will return an appropriate sibling that doesn't exist, e.g. if a file
  233. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  234. @param putNumbersInBrackets whether to add brackets around the numbers that
  235. get appended to the new filename.
  236. */
  237. File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  238. //==============================================================================
  239. /** Compares the pathnames for two files. */
  240. bool operator== (const File&) const;
  241. /** Compares the pathnames for two files. */
  242. bool operator!= (const File&) const;
  243. /** Compares the pathnames for two files. */
  244. bool operator< (const File&) const;
  245. /** Compares the pathnames for two files. */
  246. bool operator> (const File&) const;
  247. //==============================================================================
  248. /** Checks whether a file can be created or written to.
  249. @returns true if it's possible to create and write to this file. If the file
  250. doesn't already exist, this will check its parent directory to
  251. see if writing is allowed.
  252. @see setReadOnly
  253. */
  254. bool hasWriteAccess() const;
  255. /** Changes the write-permission of a file or directory.
  256. @param shouldBeReadOnly whether to add or remove write-permission
  257. @param applyRecursively if the file is a directory and this is true, it will
  258. recurse through all the subfolders changing the permissions
  259. of all files
  260. @returns true if it manages to change the file's permissions.
  261. @see hasWriteAccess
  262. */
  263. bool setReadOnly (bool shouldBeReadOnly,
  264. bool applyRecursively = false) const;
  265. /** Changes the execute-permissions of a file.
  266. @param shouldBeExecutable whether to add or remove execute-permission
  267. @returns true if it manages to change the file's permissions.
  268. */
  269. bool setExecutePermission (bool shouldBeExecutable) const;
  270. /** Returns true if this file is a hidden or system file.
  271. The criteria for deciding whether a file is hidden are platform-dependent.
  272. */
  273. bool isHidden() const;
  274. /** Returns a unique identifier for the file, if one is available.
  275. Depending on the OS and file-system, this may be a unix inode number or
  276. a win32 file identifier, or 0 if it fails to find one. The number will
  277. be unique on the filesystem, but not globally.
  278. */
  279. uint64 getFileIdentifier() const;
  280. //==============================================================================
  281. /** Returns the last modification time of this file.
  282. @returns the time, or an invalid time if the file doesn't exist.
  283. @see setLastModificationTime, getLastAccessTime, getCreationTime
  284. */
  285. Time getLastModificationTime() const;
  286. /** Returns the last time this file was accessed.
  287. @returns the time, or an invalid time if the file doesn't exist.
  288. @see setLastAccessTime, getLastModificationTime, getCreationTime
  289. */
  290. Time getLastAccessTime() const;
  291. /** Returns the time that this file was created.
  292. @returns the time, or an invalid time if the file doesn't exist.
  293. @see getLastModificationTime, getLastAccessTime
  294. */
  295. Time getCreationTime() const;
  296. /** Changes the modification time for this file.
  297. @param newTime the time to apply to the file
  298. @returns true if it manages to change the file's time.
  299. @see getLastModificationTime, setLastAccessTime, setCreationTime
  300. */
  301. bool setLastModificationTime (Time newTime) const;
  302. /** Changes the last-access time for this file.
  303. @param newTime the time to apply to the file
  304. @returns true if it manages to change the file's time.
  305. @see getLastAccessTime, setLastModificationTime, setCreationTime
  306. */
  307. bool setLastAccessTime (Time newTime) const;
  308. /** Changes the creation date for this file.
  309. @param newTime the time to apply to the file
  310. @returns true if it manages to change the file's time.
  311. @see getCreationTime, setLastModificationTime, setLastAccessTime
  312. */
  313. bool setCreationTime (Time newTime) const;
  314. /** If possible, this will try to create a version string for the given file.
  315. The OS may be able to look at the file and give a version for it - e.g. with
  316. executables, bundles, dlls, etc. If no version is available, this will
  317. return an empty string.
  318. */
  319. String getVersion() const;
  320. //==============================================================================
  321. /** Creates an empty file if it doesn't already exist.
  322. If the file that this object refers to doesn't exist, this will create a file
  323. of zero size.
  324. If it already exists or is a directory, this method will do nothing.
  325. If the parent directories of the File do not exist then this method will
  326. recursively create the parent directories.
  327. @returns a result to indicate whether the file was created successfully,
  328. or an error message if it failed.
  329. @see createDirectory
  330. */
  331. Result create() const;
  332. /** Creates a new directory for this filename.
  333. This will try to create the file as a directory, and will also create
  334. any parent directories it needs in order to complete the operation.
  335. @returns a result to indicate whether the directory was created successfully, or
  336. an error message if it failed.
  337. @see create
  338. */
  339. Result createDirectory() const;
  340. /** Deletes a file.
  341. If this file is actually a directory, it may not be deleted correctly if it
  342. contains files. See deleteRecursively() as a better way of deleting directories.
  343. If this file is a symlink, then the symlink will be deleted and not the target
  344. of the symlink.
  345. @returns true if the file has been successfully deleted (or if it didn't exist to
  346. begin with).
  347. @see deleteRecursively
  348. */
  349. bool deleteFile() const;
  350. /** Deletes a file or directory and all its subdirectories.
  351. If this file is a directory, this will try to delete it and all its subfolders. If
  352. it's just a file, it will just try to delete the file.
  353. @param followSymlinks If true, then any symlink pointing to a directory will also
  354. recursively delete the contents of that directory
  355. @returns true if the file and all its subfolders have been successfully
  356. deleted (or if it didn't exist to begin with).
  357. @see deleteFile
  358. */
  359. bool deleteRecursively (bool followSymlinks = false) const;
  360. /** Moves this file or folder to the trash.
  361. @returns true if the operation succeeded. It could fail if the trash is full, or
  362. if the file is write-protected, so you should check the return value
  363. and act appropriately.
  364. */
  365. bool moveToTrash() const;
  366. /** Moves or renames a file.
  367. Tries to move a file to a different location.
  368. If the target file already exists, this will attempt to delete it first, and
  369. will fail if this can't be done.
  370. Note that the destination file isn't the directory to put it in, it's the actual
  371. filename that you want the new file to have.
  372. Also note that on some OSes (e.g. Windows), moving files between different
  373. volumes may not be possible.
  374. @returns true if the operation succeeds
  375. */
  376. bool moveFileTo (const File& targetLocation) const;
  377. /** Copies a file.
  378. Tries to copy a file to a different location.
  379. If the target file already exists, this will attempt to delete it first, and
  380. will fail if this can't be done.
  381. @returns true if the operation succeeds
  382. */
  383. bool copyFileTo (const File& targetLocation) const;
  384. /** Replaces a file.
  385. Replace the file in the given location, assuming the replaced files identity.
  386. Depending on the file system this will preserve file attributes such as
  387. creation date, short file name, etc.
  388. If replacement succeeds the original file is deleted.
  389. @returns true if the operation succeeds
  390. */
  391. bool replaceFileIn (const File& targetLocation) const;
  392. /** Copies a directory.
  393. Tries to copy an entire directory, recursively.
  394. If this file isn't a directory or if any target files can't be created, this
  395. will return false.
  396. @param newDirectory the directory that this one should be copied to. Note that this
  397. is the name of the actual directory to create, not the directory
  398. into which the new one should be placed, so there must be enough
  399. write privileges to create it if it doesn't exist. Any files inside
  400. it will be overwritten by similarly named ones that are copied.
  401. */
  402. bool copyDirectoryTo (const File& newDirectory) const;
  403. //==============================================================================
  404. /** Used in file searching, to specify whether to return files, directories, or both.
  405. */
  406. enum TypesOfFileToFind
  407. {
  408. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  409. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  410. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  411. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  412. };
  413. /** Searches this directory for files matching a wildcard pattern.
  414. Assuming that this file is a directory, this method will search it
  415. for either files or subdirectories whose names match a filename pattern.
  416. Note that the order in which files are returned is completely undefined!
  417. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  418. return files, directories, or both. If the ignoreHiddenFiles flag
  419. is also added to this value, hidden files won't be returned
  420. @param searchRecursively if true, all subdirectories will be recursed into to do
  421. an exhaustive search
  422. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  423. @returns the set of files that were found
  424. @see getNumberOfChildFiles, RangedDirectoryIterator
  425. */
  426. Array<File> findChildFiles (int whatToLookFor,
  427. bool searchRecursively,
  428. const String& wildCardPattern = "*") const;
  429. /** Searches inside a directory for files matching a wildcard pattern.
  430. Note that there's a newer, better version of this method which returns the results
  431. array, and in almost all cases, you should use that one instead! This one is kept around
  432. mainly for legacy code to use.
  433. */
  434. int findChildFiles (Array<File>& results, int whatToLookFor,
  435. bool searchRecursively, const String& wildCardPattern = "*") const;
  436. /** Searches inside a directory and counts how many files match a wildcard pattern.
  437. Assuming that this file is a directory, this method will search it
  438. for either files or subdirectories whose names match a filename pattern,
  439. and will return the number of matches found.
  440. This isn't a recursive call, and will only search this directory, not
  441. its children.
  442. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  443. count files, directories, or both. If the ignoreHiddenFiles flag
  444. is also added to this value, hidden files won't be counted
  445. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  446. @returns the number of matches found
  447. @see findChildFiles, RangedDirectoryIterator
  448. */
  449. int getNumberOfChildFiles (int whatToLookFor,
  450. const String& wildCardPattern = "*") const;
  451. /** Returns true if this file is a directory that contains one or more subdirectories.
  452. @see isDirectory, findChildFiles
  453. */
  454. bool containsSubDirectories() const;
  455. //==============================================================================
  456. /** Creates a stream to read from this file.
  457. Note that this is an old method, and actually it's usually best to avoid it and
  458. instead use an RAII pattern with an FileInputStream directly, e.g.
  459. @code
  460. FileInputStream input (fileToOpen);
  461. if (input.openedOk())
  462. {
  463. input.read (etc...
  464. }
  465. @endcode
  466. @returns a stream that will read from this file (initially positioned at the
  467. start of the file), or nullptr if the file can't be opened for some reason
  468. @see createOutputStream, loadFileAsData
  469. */
  470. std::unique_ptr<FileInputStream> createInputStream() const;
  471. /** Creates a stream to write to this file.
  472. Note that this is an old method, and actually it's usually best to avoid it and
  473. instead use an RAII pattern with an FileOutputStream directly, e.g.
  474. @code
  475. FileOutputStream output (fileToOpen);
  476. if (output.openedOk())
  477. {
  478. output.read etc...
  479. }
  480. @endcode
  481. If the file exists, the stream that is returned will be positioned ready for
  482. writing at the end of the file. If you want to write to the start of the file,
  483. replacing the existing content, then you can do the following:
  484. @code
  485. FileOutputStream output (fileToOverwrite);
  486. if (output.openedOk())
  487. {
  488. output.setPosition (0);
  489. output.truncate();
  490. ...
  491. }
  492. @endcode
  493. @returns a stream that will write to this file (initially positioned at the
  494. end of the file), or nullptr if the file can't be opened for some reason
  495. @see createInputStream, appendData, appendText
  496. */
  497. std::unique_ptr<FileOutputStream> createOutputStream (size_t bufferSize = 0x8000) const;
  498. //==============================================================================
  499. /** Loads a file's contents into memory as a block of binary data.
  500. Of course, trying to load a very large file into memory will blow up, so
  501. it's better to check first.
  502. @param result the data block to which the file's contents should be appended - note
  503. that if the memory block might already contain some data, you
  504. might want to clear it first
  505. @returns true if the file could all be read into memory
  506. */
  507. bool loadFileAsData (MemoryBlock& result) const;
  508. /** Reads a file into memory as a string.
  509. Attempts to load the entire file as a zero-terminated string.
  510. This makes use of InputStream::readEntireStreamAsString, which can
  511. read either UTF-16 or UTF-8 file formats.
  512. */
  513. String loadFileAsString() const;
  514. /** Reads the contents of this file as text and splits it into lines, which are
  515. appended to the given StringArray.
  516. */
  517. void readLines (StringArray& destLines) const;
  518. //==============================================================================
  519. /** Appends a block of binary data to the end of the file.
  520. This will try to write the given buffer to the end of the file.
  521. @returns false if it can't write to the file for some reason
  522. */
  523. bool appendData (const void* dataToAppend,
  524. size_t numberOfBytes) const;
  525. /** Replaces this file's contents with a given block of data.
  526. This will delete the file and replace it with the given data.
  527. A nice feature of this method is that it's safe - instead of deleting
  528. the file first and then re-writing it, it creates a new temporary file,
  529. writes the data to that, and then moves the new file to replace the existing
  530. file. This means that if the power gets pulled out or something crashes,
  531. you're a lot less likely to end up with a corrupted or unfinished file..
  532. Returns true if the operation succeeds, or false if it fails.
  533. @see appendText
  534. */
  535. bool replaceWithData (const void* dataToWrite,
  536. size_t numberOfBytes) const;
  537. /** Appends a string to the end of the file.
  538. This will try to append a text string to the file, as either 16-bit unicode
  539. or 8-bit characters in the default system encoding.
  540. It can also write the 'ff fe' unicode header bytes before the text to indicate
  541. the endianness of the file.
  542. If lineEndings is nullptr, then line endings in the text won't be modified. If you
  543. pass "\\n" or "\\r\\n" then this function will replace any existing line feeds.
  544. @see replaceWithText
  545. */
  546. bool appendText (const String& textToAppend,
  547. bool asUnicode = false,
  548. bool writeUnicodeHeaderBytes = false,
  549. const char* lineEndings = "\r\n") const;
  550. /** Replaces this file's contents with a given text string.
  551. This will delete the file and replace it with the given text.
  552. A nice feature of this method is that it's safe - instead of deleting
  553. the file first and then re-writing it, it creates a new temporary file,
  554. writes the text to that, and then moves the new file to replace the existing
  555. file. This means that if the power gets pulled out or something crashes,
  556. you're a lot less likely to end up with an empty file..
  557. For an explanation of the parameters here, see the appendText() method.
  558. Returns true if the operation succeeds, or false if it fails.
  559. @see appendText
  560. */
  561. bool replaceWithText (const String& textToWrite,
  562. bool asUnicode = false,
  563. bool writeUnicodeHeaderBytes = false,
  564. const char* lineEndings = "\r\n") const;
  565. /** Attempts to scan the contents of this file and compare it to another file, returning
  566. true if this is possible and they match byte-for-byte.
  567. */
  568. bool hasIdenticalContentTo (const File& other) const;
  569. //==============================================================================
  570. /** Creates a set of files to represent each file root.
  571. e.g. on Windows this will create files for "c:\", "d:\" etc according
  572. to which ones are available. On the Mac/Linux, this will probably
  573. just add a single entry for "/".
  574. */
  575. static void findFileSystemRoots (Array<File>& results);
  576. /** Finds the name of the drive on which this file lives.
  577. @returns the volume label of the drive, or an empty string if this isn't possible
  578. */
  579. String getVolumeLabel() const;
  580. /** Returns the serial number of the volume on which this file lives.
  581. @returns the serial number, or zero if there's a problem doing this
  582. */
  583. int getVolumeSerialNumber() const;
  584. /** Returns the number of bytes free on the drive that this file lives on.
  585. @returns the number of bytes free, or 0 if there's a problem finding this out
  586. @see getVolumeTotalSize
  587. */
  588. int64 getBytesFreeOnVolume() const;
  589. /** Returns the total size of the drive that contains this file.
  590. @returns the total number of bytes that the volume can hold
  591. @see getBytesFreeOnVolume
  592. */
  593. int64 getVolumeTotalSize() const;
  594. /** Returns true if this file is on a CD or DVD drive. */
  595. bool isOnCDRomDrive() const;
  596. /** Returns true if this file is on a hard disk.
  597. This will fail if it's a network drive, but will still be true for
  598. removable hard-disks.
  599. */
  600. bool isOnHardDisk() const;
  601. /** Returns true if this file is on a removable disk drive.
  602. This might be a usb-drive, a CD-rom, or maybe a network drive.
  603. */
  604. bool isOnRemovableDrive() const;
  605. //==============================================================================
  606. /** Launches the file as a process.
  607. - if the file is executable, this will run it.
  608. - if it's a document of some kind, it will launch the document with its
  609. default viewer application.
  610. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  611. @see revealToUser
  612. */
  613. bool startAsProcess (const String& parameters = String()) const;
  614. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  615. @see startAsProcess
  616. */
  617. void revealToUser() const;
  618. //==============================================================================
  619. /** A set of types of location that can be passed to the getSpecialLocation() method.
  620. */
  621. enum SpecialLocationType
  622. {
  623. /** The user's home folder. This is the same as using File ("~"). */
  624. userHomeDirectory,
  625. /** The user's default documents folder. On Windows, this might be the user's
  626. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  627. doesn't tend to have one of these, so it might just return their home folder.
  628. */
  629. userDocumentsDirectory,
  630. /** The folder that contains the user's desktop objects. */
  631. userDesktopDirectory,
  632. /** The most likely place where a user might store their music files. */
  633. userMusicDirectory,
  634. /** The most likely place where a user might store their movie files. */
  635. userMoviesDirectory,
  636. /** The most likely place where a user might store their picture files. */
  637. userPicturesDirectory,
  638. /** The folder in which applications store their persistent user-specific settings.
  639. On Windows, this might be "\Documents and Settings\username\Application Data".
  640. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  641. always create your own sub-folder to put them in, to avoid making a mess.
  642. On GNU/Linux it is "~/.config".
  643. */
  644. userApplicationDataDirectory,
  645. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  646. of the computer, rather than just the current user.
  647. On the Mac it'll be "/Library", on Windows, it could be something like
  648. "\Documents and Settings\All Users\Application Data".
  649. On GNU/Linux it is "/opt".
  650. Depending on the setup, this folder may be read-only.
  651. */
  652. commonApplicationDataDirectory,
  653. /** A place to put documents which are shared by all users of the machine.
  654. On Windows this may be somewhere like "C:\Users\Public\Documents", on OSX it
  655. will be something like "/Users/Shared". Other OSes may have no such concept
  656. though, so be careful.
  657. */
  658. commonDocumentsDirectory,
  659. /** The folder that should be used for temporary files.
  660. Always delete them when you're finished, to keep the user's computer tidy!
  661. */
  662. tempDirectory,
  663. /** Returns this application's executable file.
  664. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  665. host app.
  666. On the mac this will return the unix binary, not the package folder - see
  667. currentApplicationFile for that.
  668. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  669. file link, invokedExecutableFile will return the name of the link.
  670. */
  671. currentExecutableFile,
  672. /** Returns this application's location.
  673. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  674. host app.
  675. On the mac this will return the package folder (if it's in one), not the unix binary
  676. that's inside it - compare with currentExecutableFile.
  677. */
  678. currentApplicationFile,
  679. /** Returns the file that was invoked to launch this executable.
  680. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  681. will return the name of the link that was used, whereas currentExecutableFile will return
  682. the actual location of the target executable.
  683. */
  684. invokedExecutableFile,
  685. /** In a plugin, this will return the path of the host executable. */
  686. hostApplicationPath,
  687. #if JUCE_WINDOWS || DOXYGEN
  688. /** On a Windows machine, returns the location of the Windows/System32 folder. */
  689. windowsSystemDirectory,
  690. #endif
  691. /** The directory in which applications normally get installed.
  692. So on windows, this would be something like "C:\Program Files", on the
  693. Mac "/Applications", or "/usr" on linux.
  694. */
  695. globalApplicationsDirectory,
  696. #if JUCE_WINDOWS || DOXYGEN
  697. /** On a Windows machine, returns the directory in which 32 bit applications
  698. normally get installed. On a 64 bit machine this would be something like
  699. "C:\Program Files (x86)", whereas for 32 bit machines this would match
  700. globalApplicationsDirectory and be something like "C:\Program Files".
  701. @see globalApplicationsDirectory
  702. */
  703. globalApplicationsDirectoryX86
  704. #endif
  705. };
  706. /** Finds the location of a special type of file or directory, such as a home folder or
  707. documents folder.
  708. @see SpecialLocationType
  709. */
  710. static File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  711. //==============================================================================
  712. /** Returns a temporary file in the system's temp directory.
  713. This will try to return the name of a non-existent temp file.
  714. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  715. */
  716. static File createTempFile (StringRef fileNameEnding);
  717. //==============================================================================
  718. /** Returns the current working directory.
  719. @see setAsCurrentWorkingDirectory
  720. */
  721. static File getCurrentWorkingDirectory();
  722. /** Sets the current working directory to be this file.
  723. For this to work the file must point to a valid directory.
  724. @returns true if the current directory has been changed.
  725. @see getCurrentWorkingDirectory
  726. */
  727. bool setAsCurrentWorkingDirectory() const;
  728. //==============================================================================
  729. /** The system-specific file separator character.
  730. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  731. */
  732. static juce_wchar getSeparatorChar();
  733. /** The system-specific file separator character, as a string.
  734. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  735. */
  736. static StringRef getSeparatorString();
  737. //==============================================================================
  738. /** Returns a version of a filename with any illegal characters removed.
  739. This will return a copy of the given string after removing characters
  740. that are not allowed in a legal filename, and possibly shortening the
  741. string if it's too long.
  742. Because this will remove slashes, don't use it on an absolute pathname - use
  743. createLegalPathName() for that.
  744. @see createLegalPathName
  745. */
  746. static String createLegalFileName (const String& fileNameToFix);
  747. /** Returns a version of a path with any illegal characters removed.
  748. Similar to createLegalFileName(), but this won't remove slashes, so can
  749. be used on a complete pathname.
  750. @see createLegalFileName
  751. */
  752. static String createLegalPathName (const String& pathNameToFix);
  753. /** Indicates whether filenames are case-sensitive on the current operating system. */
  754. static bool areFileNamesCaseSensitive();
  755. /** Returns true if the string seems to be a fully-specified absolute path. */
  756. static bool isAbsolutePath (StringRef path);
  757. /** Creates a file that simply contains this string, without doing the sanity-checking
  758. that the normal constructors do.
  759. Best to avoid this unless you really know what you're doing.
  760. */
  761. static File createFileWithoutCheckingPath (const String& absolutePath) noexcept;
  762. /** Adds a separator character to the end of a path if it doesn't already have one. */
  763. static String addTrailingSeparator (const String& path);
  764. //==============================================================================
  765. /** Tries to create a symbolic link and returns a boolean to indicate success */
  766. bool createSymbolicLink (const File& linkFileToCreate, bool overwriteExisting) const;
  767. /** Returns true if this file is a link or alias that can be followed using getLinkedTarget(). */
  768. bool isSymbolicLink() const;
  769. /** If this file is a link or alias, this returns the file that it points to.
  770. If the file isn't actually link, it'll just return itself.
  771. */
  772. File getLinkedTarget() const;
  773. /** Create a symbolic link to a native path and return a boolean to indicate success.
  774. Use this method if you want to create a link to a relative path or a special native
  775. file path (such as a device file on Windows).
  776. */
  777. static bool createSymbolicLink (const File& linkFileToCreate,
  778. const String& nativePathOfTarget,
  779. bool overwriteExisting);
  780. /** This returns the native path that the symbolic link points to. The returned path
  781. is a native path of the current OS and can be a relative, absolute or special path. */
  782. String getNativeLinkedTarget() const;
  783. #if JUCE_WINDOWS || DOXYGEN
  784. /** Windows ONLY - Creates a win32 .LNK shortcut file that links to this file. */
  785. bool createShortcut (const String& description, const File& linkFileToCreate) const;
  786. /** Windows ONLY - Returns true if this is a win32 .LNK file. */
  787. bool isShortcut() const;
  788. #else
  789. #endif
  790. //==============================================================================
  791. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  792. /** OSX ONLY - Finds the OSType of a file from the its resources. */
  793. OSType getMacOSType() const;
  794. /** OSX ONLY - Returns true if this file is actually a bundle. */
  795. bool isBundle() const;
  796. #endif
  797. #if JUCE_MAC || DOXYGEN
  798. /** OSX ONLY - Adds this file to the OSX dock */
  799. void addToDock() const;
  800. #endif
  801. //==============================================================================
  802. /** Comparator for files */
  803. struct NaturalFileComparator
  804. {
  805. NaturalFileComparator (bool shouldPutFoldersFirst) noexcept : foldersFirst (shouldPutFoldersFirst) {}
  806. int compareElements (const File& firstFile, const File& secondFile) const
  807. {
  808. if (foldersFirst && (firstFile.isDirectory() != secondFile.isDirectory()))
  809. return firstFile.isDirectory() ? -1 : 1;
  810. #if NAMES_ARE_CASE_SENSITIVE
  811. return firstFile.getFullPathName().compareNatural (secondFile.getFullPathName(), true);
  812. #else
  813. return firstFile.getFullPathName().compareNatural (secondFile.getFullPathName(), false);
  814. #endif
  815. }
  816. bool foldersFirst;
  817. };
  818. /* These static objects are deprecated because it's too easy to accidentally use them indirectly
  819. during a static constructor, which leads to very obscure order-of-initialisation bugs.
  820. Use File::getSeparatorChar() and File::getSeparatorString(), and instead of File::nonexistent,
  821. just use File() or {}.
  822. */
  823. JUCE_DEPRECATED_STATIC (static const juce_wchar separator;)
  824. JUCE_DEPRECATED_STATIC (static const StringRef separatorString;)
  825. JUCE_DEPRECATED_STATIC (static const File nonexistent;)
  826. private:
  827. //==============================================================================
  828. String fullPath;
  829. static String parseAbsolutePath (const String&);
  830. String getPathUpToLastSlash() const;
  831. Result createDirectoryInternal (const String&) const;
  832. bool copyInternal (const File&) const;
  833. bool moveInternal (const File&) const;
  834. bool replaceInternal (const File&) const;
  835. bool setFileTimesInternal (int64 m, int64 a, int64 c) const;
  836. void getFileTimesInternal (int64& m, int64& a, int64& c) const;
  837. bool setFileReadOnlyInternal (bool) const;
  838. bool setFileExecutableInternal (bool) const;
  839. };
  840. } // namespace juce