PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/trunk/JuceLibraryCode/modules/juce_core/files/juce_File.h

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