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.

960 lines
40KB

  1. /*
  2. ==============================================================================
  3. This file is part of the juce_core module of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software 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. #ifndef JUCE_FILE_H_INCLUDED
  22. #define JUCE_FILE_H_INCLUDED
  23. #include "../containers/juce_Array.h"
  24. #include "../time/juce_Time.h"
  25. #include "../text/juce_StringArray.h"
  26. #include "../memory/juce_MemoryBlock.h"
  27. #include "../memory/juce_ScopedPointer.h"
  28. #include "../misc/juce_Result.h"
  29. class FileInputStream;
  30. class FileOutputStream;
  31. //==============================================================================
  32. /**
  33. Represents a local file or directory.
  34. This class encapsulates the absolute pathname of a file or directory, and
  35. has methods for finding out about the file and changing its properties.
  36. To read or write to the file, there are methods for returning an input or
  37. output stream.
  38. @see FileInputStream, FileOutputStream
  39. */
  40. class JUCE_API File
  41. {
  42. public:
  43. //==============================================================================
  44. /** Creates an (invalid) file object.
  45. The file is initially set to an empty path, so getFullPath() will return
  46. an empty string, and comparing the file to File::nonexistent will return
  47. true.
  48. You can use its operator= method to point it at a proper file.
  49. */
  50. File() noexcept {}
  51. /** Creates a file from an absolute path.
  52. If the path supplied is a relative path, it is taken to be relative
  53. to the current working directory (see File::getCurrentWorkingDirectory()),
  54. but this isn't a recommended way of creating a file, because you
  55. never know what the CWD is going to be.
  56. On the Mac/Linux, the path can include "~" notation for referring to
  57. user home directories.
  58. */
  59. File (const String& absolutePath);
  60. /** Creates a copy of another file object. */
  61. File (const File&);
  62. /** Destructor. */
  63. ~File() noexcept {}
  64. /** Sets the file based on an absolute pathname.
  65. If the path supplied is a relative path, it is taken to be relative
  66. to the current working directory (see File::getCurrentWorkingDirectory()),
  67. but this isn't a recommended way of creating a file, because you
  68. never know what the CWD is going to be.
  69. On the Mac/Linux, the path can include "~" notation for referring to
  70. user home directories.
  71. */
  72. File& operator= (const String& newAbsolutePath);
  73. /** Copies from another file object. */
  74. File& operator= (const File& otherFile);
  75. #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
  76. File (File&&) noexcept;
  77. File& operator= (File&&) noexcept;
  78. #endif
  79. //==============================================================================
  80. /** This static constant is used for referring to an 'invalid' file. */
  81. static const File nonexistent;
  82. //==============================================================================
  83. /** Checks whether the file actually exists.
  84. @returns true if the file exists, either as a file or a directory.
  85. @see existsAsFile, isDirectory
  86. */
  87. bool exists() const;
  88. /** Checks whether the file exists and is a file rather than a directory.
  89. @returns true only if this is a real file, false if it's a directory
  90. or doesn't exist
  91. @see exists, isDirectory
  92. */
  93. bool existsAsFile() const;
  94. /** Checks whether the file is a directory that exists.
  95. @returns true only if the file is a directory which actually exists, so
  96. false if it's a file or doesn't exist at all
  97. @see exists, existsAsFile
  98. */
  99. bool isDirectory() const;
  100. /** Returns the size of the file in bytes.
  101. @returns the number of bytes in the file, or 0 if it doesn't exist.
  102. */
  103. int64 getSize() const;
  104. /** Utility function to convert a file size in bytes to a neat string description.
  105. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  106. 2000000 would produce "2 MB", etc.
  107. */
  108. static String descriptionOfSizeInBytes (int64 bytes);
  109. //==============================================================================
  110. /** Returns the complete, absolute path of this file.
  111. This includes the filename and all its parent folders. On Windows it'll
  112. also include the drive letter prefix; on Mac or Linux it'll be a complete
  113. path starting from the root folder.
  114. If you just want the file's name, you should use getFileName() or
  115. getFileNameWithoutExtension().
  116. @see getFileName, getRelativePathFrom
  117. */
  118. const String& getFullPathName() const noexcept { return fullPath; }
  119. /** Returns the last section of the pathname.
  120. Returns just the final part of the path - e.g. if the whole path
  121. is "/moose/fish/foo.txt" this will return "foo.txt".
  122. For a directory, it returns the final part of the path - e.g. for the
  123. directory "/moose/fish" it'll return "fish".
  124. If the filename begins with a dot, it'll return the whole filename, e.g. for
  125. "/moose/.fish", it'll return ".fish"
  126. @see getFullPathName, getFileNameWithoutExtension
  127. */
  128. String getFileName() const;
  129. /** Creates a relative path that refers to a file relatively to a given directory.
  130. e.g. File ("/moose/foo.txt").getRelativePathFrom (File ("/moose/fish/haddock"))
  131. would return "../../foo.txt".
  132. If it's not possible to navigate from one file to the other, an absolute
  133. path is returned. If the paths are invalid, an empty string may also be
  134. returned.
  135. @param directoryToBeRelativeTo the directory which the resultant string will
  136. be relative to. If this is actually a file rather than
  137. a directory, its parent directory will be used instead.
  138. If it doesn't exist, it's assumed to be a directory.
  139. @see getChildFile, isAbsolutePath
  140. */
  141. String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  142. //==============================================================================
  143. /** Returns the file's extension.
  144. Returns the file extension of this file, also including the dot.
  145. e.g. "/moose/fish/foo.txt" would return ".txt"
  146. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  147. */
  148. String getFileExtension() const;
  149. /** Checks whether the file has a given extension.
  150. @param extensionToTest the extension to look for - it doesn't matter whether or
  151. not this string has a dot at the start, so ".wav" and "wav"
  152. will have the same effect. To compare with multiple extensions, this
  153. parameter can contain multiple strings, separated by semi-colons -
  154. so, for example: hasFileExtension (".jpeg;png;gif") would return
  155. true if the file has any of those three extensions.
  156. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  157. */
  158. bool hasFileExtension (const String& extensionToTest) const;
  159. /** Returns a version of this file with a different file extension.
  160. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  161. @param newExtension the new extension, either with or without a dot at the start (this
  162. doesn't make any difference). To get remove a file's extension altogether,
  163. pass an empty string into this function.
  164. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  165. */
  166. File withFileExtension (const String& newExtension) const;
  167. /** Returns the last part of the filename, without its file extension.
  168. e.g. for "/moose/fish/foo.txt" this will return "foo".
  169. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  170. */
  171. String getFileNameWithoutExtension() const;
  172. //==============================================================================
  173. /** Returns a 32-bit hash-code that identifies this file.
  174. This is based on the filename. Obviously it's possible, although unlikely, that
  175. two files will have the same hash-code.
  176. */
  177. int hashCode() const;
  178. /** Returns a 64-bit hash-code that identifies this file.
  179. This is based on the filename. Obviously it's possible, although unlikely, that
  180. two files will have the same hash-code.
  181. */
  182. int64 hashCode64() const;
  183. //==============================================================================
  184. /** Returns a file that represents a relative (or absolute) sub-path of the current one.
  185. This will find a child file or directory of the current object.
  186. e.g.
  187. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  188. File ("/moose/fish").getChildFile ("haddock/foo.txt") will produce "/moose/fish/haddock/foo.txt".
  189. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  190. If the string is actually an absolute path, it will be treated as such, e.g.
  191. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  192. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  193. */
  194. File getChildFile (String relativeOrAbsolutePath) const;
  195. /** Returns a file which is in the same directory as this one.
  196. This is equivalent to getParentDirectory().getChildFile (name).
  197. @see getChildFile, getParentDirectory
  198. */
  199. File getSiblingFile (const String& siblingFileName) const;
  200. //==============================================================================
  201. /** Returns the directory that contains this file or directory.
  202. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  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. /** Returns true if this file is a hidden or system file.
  266. The criteria for deciding whether a file is hidden are platform-dependent.
  267. */
  268. bool isHidden() const;
  269. /** If this file is a link, this returns the file that it points to.
  270. If this file isn't actually link, it'll just return itself.
  271. */
  272. File getLinkedTarget() 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. @returns true if the file has been created (or if it already existed).
  319. @see createDirectory
  320. */
  321. Result create() const;
  322. /** Creates a new directory for this filename.
  323. This will try to create the file as a directory, and fill also create
  324. any parent directories it needs in order to complete the operation.
  325. @returns a result to indicate whether the directory was created successfully, or
  326. an error message if it failed.
  327. @see create
  328. */
  329. Result createDirectory() const;
  330. /** Deletes a file.
  331. If this file is actually a directory, it may not be deleted correctly if it
  332. contains files. See deleteRecursively() as a better way of deleting directories.
  333. @returns true if the file has been successfully deleted (or if it didn't exist to
  334. begin with).
  335. @see deleteRecursively
  336. */
  337. bool deleteFile() const;
  338. /** Deletes a file or directory and all its subdirectories.
  339. If this file is a directory, this will try to delete it and all its subfolders. If
  340. it's just a file, it will just try to delete the file.
  341. @returns true if the file and all its subfolders have been successfully deleted
  342. (or if it didn't exist to begin with).
  343. @see deleteFile
  344. */
  345. bool deleteRecursively() const;
  346. /** Moves this file or folder to the trash.
  347. @returns true if the operation succeeded. It could fail if the trash is full, or
  348. if the file is write-protected, so you should check the return value
  349. and act appropriately.
  350. */
  351. bool moveToTrash() const;
  352. /** Moves or renames a file.
  353. Tries to move a file to a different location.
  354. If the target file already exists, this will attempt to delete it first, and
  355. will fail if this can't be done.
  356. Note that the destination file isn't the directory to put it in, it's the actual
  357. filename that you want the new file to have.
  358. @returns true if the operation succeeds
  359. */
  360. bool moveFileTo (const File& targetLocation) const;
  361. /** Copies a file.
  362. Tries to copy a file to a different location.
  363. If the target file already exists, this will attempt to delete it first, and
  364. will fail if this can't be done.
  365. @returns true if the operation succeeds
  366. */
  367. bool copyFileTo (const File& targetLocation) const;
  368. /** Copies a directory.
  369. Tries to copy an entire directory, recursively.
  370. If this file isn't a directory or if any target files can't be created, this
  371. will return false.
  372. @param newDirectory the directory that this one should be copied to. Note that this
  373. is the name of the actual directory to create, not the directory
  374. into which the new one should be placed, so there must be enough
  375. write privileges to create it if it doesn't exist. Any files inside
  376. it will be overwritten by similarly named ones that are copied.
  377. */
  378. bool copyDirectoryTo (const File& newDirectory) const;
  379. //==============================================================================
  380. /** Used in file searching, to specify whether to return files, directories, or both.
  381. */
  382. enum TypesOfFileToFind
  383. {
  384. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  385. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  386. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  387. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  388. };
  389. /** Searches inside a directory for files matching a wildcard pattern.
  390. Assuming that this file is a directory, this method will search it
  391. for either files or subdirectories whose names match a filename pattern.
  392. @param results an array to which File objects will be added for the
  393. files that the search comes up with
  394. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  395. return files, directories, or both. If the ignoreHiddenFiles flag
  396. is also added to this value, hidden files won't be returned
  397. @param searchRecursively if true, all subdirectories will be recursed into to do
  398. an exhaustive search
  399. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  400. @returns the number of results that have been found
  401. @see getNumberOfChildFiles, DirectoryIterator
  402. */
  403. int findChildFiles (Array<File>& results,
  404. int whatToLookFor,
  405. bool searchRecursively,
  406. const String& wildCardPattern = "*") const;
  407. /** Searches inside a directory and counts how many files match a wildcard pattern.
  408. Assuming that this file is a directory, this method will search it
  409. for either files or subdirectories whose names match a filename pattern,
  410. and will return the number of matches found.
  411. This isn't a recursive call, and will only search this directory, not
  412. its children.
  413. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  414. count files, directories, or both. If the ignoreHiddenFiles flag
  415. is also added to this value, hidden files won't be counted
  416. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  417. @returns the number of matches found
  418. @see findChildFiles, DirectoryIterator
  419. */
  420. int getNumberOfChildFiles (int whatToLookFor,
  421. const String& wildCardPattern = "*") const;
  422. /** Returns true if this file is a directory that contains one or more subdirectories.
  423. @see isDirectory, findChildFiles
  424. */
  425. bool containsSubDirectories() const;
  426. //==============================================================================
  427. /** Creates a stream to read from this file.
  428. @returns a stream that will read from this file (initially positioned at the
  429. start of the file), or nullptr if the file can't be opened for some reason
  430. @see createOutputStream, loadFileAsData
  431. */
  432. FileInputStream* createInputStream() const;
  433. /** Creates a stream to write to this file.
  434. If the file exists, the stream that is returned will be positioned ready for
  435. writing at the end of the file, so you might want to use deleteFile() first
  436. to write to an empty file.
  437. @returns a stream that will write to this file (initially positioned at the
  438. end of the file), or nullptr if the file can't be opened for some reason
  439. @see createInputStream, appendData, appendText
  440. */
  441. FileOutputStream* createOutputStream (int bufferSize = 0x8000) const;
  442. //==============================================================================
  443. /** Loads a file's contents into memory as a block of binary data.
  444. Of course, trying to load a very large file into memory will blow up, so
  445. it's better to check first.
  446. @param result the data block to which the file's contents should be appended - note
  447. that if the memory block might already contain some data, you
  448. might want to clear it first
  449. @returns true if the file could all be read into memory
  450. */
  451. bool loadFileAsData (MemoryBlock& result) const;
  452. /** Reads a file into memory as a string.
  453. Attempts to load the entire file as a zero-terminated string.
  454. This makes use of InputStream::readEntireStreamAsString, which can
  455. read either UTF-16 or UTF-8 file formats.
  456. */
  457. String loadFileAsString() const;
  458. /** Reads the contents of this file as text and splits it into lines, which are
  459. appended to the given StringArray.
  460. */
  461. void readLines (StringArray& destLines) const;
  462. //==============================================================================
  463. /** Appends a block of binary data to the end of the file.
  464. This will try to write the given buffer to the end of the file.
  465. @returns false if it can't write to the file for some reason
  466. */
  467. bool appendData (const void* dataToAppend,
  468. size_t numberOfBytes) const;
  469. /** Replaces this file's contents with a given block of data.
  470. This will delete the file and replace it with the given data.
  471. A nice feature of this method is that it's safe - instead of deleting
  472. the file first and then re-writing it, it creates a new temporary file,
  473. writes the data to that, and then moves the new file to replace the existing
  474. file. This means that if the power gets pulled out or something crashes,
  475. you're a lot less likely to end up with a corrupted or unfinished file..
  476. Returns true if the operation succeeds, or false if it fails.
  477. @see appendText
  478. */
  479. bool replaceWithData (const void* dataToWrite,
  480. size_t numberOfBytes) const;
  481. /** Appends a string to the end of the file.
  482. This will try to append a text string to the file, as either 16-bit unicode
  483. or 8-bit characters in the default system encoding.
  484. It can also write the 'ff fe' unicode header bytes before the text to indicate
  485. the endianness of the file.
  486. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  487. @see replaceWithText
  488. */
  489. bool appendText (const String& textToAppend,
  490. bool asUnicode = false,
  491. bool writeUnicodeHeaderBytes = false) const;
  492. /** Replaces this file's contents with a given text string.
  493. This will delete the file and replace it with the given text.
  494. A nice feature of this method is that it's safe - instead of deleting
  495. the file first and then re-writing it, it creates a new temporary file,
  496. writes the text to that, and then moves the new file to replace the existing
  497. file. This means that if the power gets pulled out or something crashes,
  498. you're a lot less likely to end up with an empty file..
  499. For an explanation of the parameters here, see the appendText() method.
  500. Returns true if the operation succeeds, or false if it fails.
  501. @see appendText
  502. */
  503. bool replaceWithText (const String& textToWrite,
  504. bool asUnicode = false,
  505. bool writeUnicodeHeaderBytes = false) const;
  506. /** Attempts to scan the contents of this file and compare it to another file, returning
  507. true if this is possible and they match byte-for-byte.
  508. */
  509. bool hasIdenticalContentTo (const File& other) const;
  510. //==============================================================================
  511. /** Creates a set of files to represent each file root.
  512. e.g. on Windows this will create files for "c:\", "d:\" etc according
  513. to which ones are available. On the Mac/Linux, this will probably
  514. just add a single entry for "/".
  515. */
  516. static void findFileSystemRoots (Array<File>& results);
  517. /** Finds the name of the drive on which this file lives.
  518. @returns the volume label of the drive, or an empty string if this isn't possible
  519. */
  520. String getVolumeLabel() const;
  521. /** Returns the serial number of the volume on which this file lives.
  522. @returns the serial number, or zero if there's a problem doing this
  523. */
  524. int getVolumeSerialNumber() const;
  525. /** Returns the number of bytes free on the drive that this file lives on.
  526. @returns the number of bytes free, or 0 if there's a problem finding this out
  527. @see getVolumeTotalSize
  528. */
  529. int64 getBytesFreeOnVolume() const;
  530. /** Returns the total size of the drive that contains this file.
  531. @returns the total number of bytes that the volume can hold
  532. @see getBytesFreeOnVolume
  533. */
  534. int64 getVolumeTotalSize() const;
  535. /** Returns true if this file is on a CD or DVD drive. */
  536. bool isOnCDRomDrive() const;
  537. /** Returns true if this file is on a hard disk.
  538. This will fail if it's a network drive, but will still be true for
  539. removable hard-disks.
  540. */
  541. bool isOnHardDisk() const;
  542. /** Returns true if this file is on a removable disk drive.
  543. This might be a usb-drive, a CD-rom, or maybe a network drive.
  544. */
  545. bool isOnRemovableDrive() const;
  546. //==============================================================================
  547. /** Launches the file as a process.
  548. - if the file is executable, this will run it.
  549. - if it's a document of some kind, it will launch the document with its
  550. default viewer application.
  551. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  552. @see revealToUser
  553. */
  554. bool startAsProcess (const String& parameters = String::empty) const;
  555. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  556. @see startAsProcess
  557. */
  558. void revealToUser() const;
  559. //==============================================================================
  560. /** A set of types of location that can be passed to the getSpecialLocation() method.
  561. */
  562. enum SpecialLocationType
  563. {
  564. /** The user's home folder. This is the same as using File ("~"). */
  565. userHomeDirectory,
  566. /** The user's default documents folder. On Windows, this might be the user's
  567. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  568. doesn't tend to have one of these, so it might just return their home folder.
  569. */
  570. userDocumentsDirectory,
  571. /** The folder that contains the user's desktop objects. */
  572. userDesktopDirectory,
  573. /** The folder in which applications store their persistent user-specific settings.
  574. On Windows, this might be "\Documents and Settings\username\Application Data".
  575. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  576. always create your own sub-folder to put them in, to avoid making a mess.
  577. */
  578. userApplicationDataDirectory,
  579. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  580. of the computer, rather than just the current user.
  581. On the Mac it'll be "/Library", on Windows, it could be something like
  582. "\Documents and Settings\All Users\Application Data".
  583. Depending on the setup, this folder may be read-only.
  584. */
  585. commonApplicationDataDirectory,
  586. /** The folder that should be used for temporary files.
  587. Always delete them when you're finished, to keep the user's computer tidy!
  588. */
  589. tempDirectory,
  590. /** Returns this application's executable file.
  591. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  592. host app.
  593. On the mac this will return the unix binary, not the package folder - see
  594. currentApplicationFile for that.
  595. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  596. file link, invokedExecutableFile will return the name of the link.
  597. */
  598. currentExecutableFile,
  599. /** Returns this application's location.
  600. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  601. host app.
  602. On the mac this will return the package folder (if it's in one), not the unix binary
  603. that's inside it - compare with currentExecutableFile.
  604. */
  605. currentApplicationFile,
  606. /** Returns the file that was invoked to launch this executable.
  607. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  608. will return the name of the link that was used, whereas currentExecutableFile will return
  609. the actual location of the target executable.
  610. */
  611. invokedExecutableFile,
  612. /** In a plugin, this will return the path of the host executable. */
  613. hostApplicationPath,
  614. /** The directory in which applications normally get installed.
  615. So on windows, this would be something like "c:\program files", on the
  616. Mac "/Applications", or "/usr" on linux.
  617. */
  618. globalApplicationsDirectory,
  619. /** The most likely place where a user might store their music files. */
  620. userMusicDirectory,
  621. /** The most likely place where a user might store their movie files. */
  622. userMoviesDirectory,
  623. /** The most likely place where a user might store their picture files. */
  624. userPicturesDirectory
  625. };
  626. /** Finds the location of a special type of file or directory, such as a home folder or
  627. documents folder.
  628. @see SpecialLocationType
  629. */
  630. static File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  631. //==============================================================================
  632. /** Returns a temporary file in the system's temp directory.
  633. This will try to return the name of a non-existent temp file.
  634. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  635. */
  636. static File createTempFile (const String& fileNameEnding);
  637. //==============================================================================
  638. /** Returns the current working directory.
  639. @see setAsCurrentWorkingDirectory
  640. */
  641. static File getCurrentWorkingDirectory();
  642. /** Sets the current working directory to be this file.
  643. For this to work the file must point to a valid directory.
  644. @returns true if the current directory has been changed.
  645. @see getCurrentWorkingDirectory
  646. */
  647. bool setAsCurrentWorkingDirectory() const;
  648. //==============================================================================
  649. /** The system-specific file separator character.
  650. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  651. */
  652. static const juce_wchar separator;
  653. /** The system-specific file separator character, as a string.
  654. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  655. */
  656. static const String separatorString;
  657. //==============================================================================
  658. /** Returns a version of a filename with any illegal characters removed.
  659. This will return a copy of the given string after removing characters
  660. that are not allowed in a legal filename, and possibly shortening the
  661. string if it's too long.
  662. Because this will remove slashes, don't use it on an absolute pathname - use
  663. createLegalPathName() for that.
  664. @see createLegalPathName
  665. */
  666. static String createLegalFileName (const String& fileNameToFix);
  667. /** Returns a version of a path with any illegal characters removed.
  668. Similar to createLegalFileName(), but this won't remove slashes, so can
  669. be used on a complete pathname.
  670. @see createLegalFileName
  671. */
  672. static String createLegalPathName (const String& pathNameToFix);
  673. /** Indicates whether filenames are case-sensitive on the current operating system. */
  674. static bool areFileNamesCaseSensitive();
  675. /** Returns true if the string seems to be a fully-specified absolute path. */
  676. static bool isAbsolutePath (const String& path);
  677. /** Creates a file that simply contains this string, without doing the sanity-checking
  678. that the normal constructors do.
  679. Best to avoid this unless you really know what you're doing.
  680. */
  681. static File createFileWithoutCheckingPath (const String& absolutePath) noexcept;
  682. /** Adds a separator character to the end of a path if it doesn't already have one. */
  683. static String addTrailingSeparator (const String& path);
  684. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  685. //==============================================================================
  686. /** OSX ONLY - Finds the OSType of a file from the its resources. */
  687. OSType getMacOSType() const;
  688. /** OSX ONLY - Returns true if this file is actually a bundle. */
  689. bool isBundle() const;
  690. #endif
  691. #if JUCE_MAC || DOXYGEN
  692. /** OSX ONLY - Adds this file to the OSX dock */
  693. void addToDock() const;
  694. #endif
  695. #if JUCE_WINDOWS
  696. /** Windows ONLY - Creates a win32 .LNK shortcut file that links to this file. */
  697. bool createLink (const String& description, const File& linkFileToCreate) const;
  698. #endif
  699. private:
  700. //==============================================================================
  701. String fullPath;
  702. static String parseAbsolutePath (const String&);
  703. String getPathUpToLastSlash() const;
  704. Result createDirectoryInternal (const String&) const;
  705. bool copyInternal (const File&) const;
  706. bool moveInternal (const File&) const;
  707. bool setFileTimesInternal (int64 m, int64 a, int64 c) const;
  708. void getFileTimesInternal (int64& m, int64& a, int64& c) const;
  709. bool setFileReadOnlyInternal (bool) const;
  710. };
  711. #endif // JUCE_FILE_H_INCLUDED