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.

1084 lines
45KB

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