Audio plugin host https://kx.studio/carla
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.

798 lines
33KB

  1. /*
  2. ==============================================================================
  3. This file is part of the Water library.
  4. Copyright (c) 2016 ROLI Ltd.
  5. Copyright (C) 2017-2022 Filipe Coelho <falktx@falktx.com>
  6. Permission is granted to use this software under the terms of the ISC license
  7. http://www.isc.org/downloads/software-support-policy/isc-license/
  8. Permission to use, copy, modify, and/or distribute this software for any
  9. purpose with or without fee is hereby granted, provided that the above
  10. copyright notice and this permission notice appear in all copies.
  11. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  12. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  13. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  14. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  15. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  16. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  17. OF THIS SOFTWARE.
  18. ==============================================================================
  19. */
  20. #ifndef WATER_FILE_H_INCLUDED
  21. #define WATER_FILE_H_INCLUDED
  22. #include "../containers/Array.h"
  23. #include "../misc/Result.h"
  24. #include "../text/String.h"
  25. #include <vector>
  26. namespace water {
  27. //==============================================================================
  28. /**
  29. Represents a local file or directory.
  30. This class encapsulates the absolute pathname of a file or directory, and
  31. has methods for finding out about the file and changing its properties.
  32. To read or write to the file, there are methods for returning an input or
  33. output stream.
  34. @see FileInputStream, FileOutputStream
  35. */
  36. class File
  37. {
  38. public:
  39. //==============================================================================
  40. /** Creates an (invalid) file object.
  41. The file is initially set to an empty path, so getFullPathName() will return
  42. an empty string.
  43. You can use its operator= method to point it at a proper file.
  44. */
  45. File() noexcept;
  46. /** Creates a file from an absolute path.
  47. If the path supplied is a relative path, it is taken to be relative
  48. to the current working directory (see File::getCurrentWorkingDirectory()),
  49. but this isn't a recommended way of creating a file, because you
  50. never know what the CWD is going to be.
  51. On the Mac/Linux, the path can include "~" notation for referring to
  52. user home directories.
  53. */
  54. File (const String& absolutePath);
  55. /** Creates a copy of another file object. */
  56. File (const File&);
  57. /** Destructor. */
  58. ~File() noexcept {}
  59. /** Sets the file based on an absolute pathname.
  60. If the path supplied is a relative path, it is taken to be relative
  61. to the current working directory (see File::getCurrentWorkingDirectory()),
  62. but this isn't a recommended way of creating a file, because you
  63. never know what the CWD is going to be.
  64. On the Mac/Linux, the path can include "~" notation for referring to
  65. user home directories.
  66. */
  67. File& operator= (const String& newAbsolutePath);
  68. /** Copies from another file object. */
  69. File& operator= (const File& otherFile);
  70. //==============================================================================
  71. /** Checks whether the file actually exists.
  72. @returns true if the file exists, either as a file or a directory.
  73. @see existsAsFile, isDirectory
  74. */
  75. bool exists() const;
  76. /** Checks whether the file exists and is a file rather than a directory.
  77. @returns true only if this is a real file, false if it's a directory
  78. or doesn't exist
  79. @see exists, isDirectory
  80. */
  81. bool existsAsFile() const;
  82. /** Checks whether the file is a directory that exists.
  83. @returns true only if the file is a directory which actually exists, so
  84. false if it's a file or doesn't exist at all
  85. @see exists, existsAsFile
  86. */
  87. bool isDirectory() const;
  88. /** Checks whether the file is invalid (empty path).
  89. */
  90. bool isNull() const;
  91. /** Checks whether the file is valid (non-empty path).
  92. */
  93. bool isNotNull() const;
  94. /** Returns the size of the file in bytes.
  95. @returns the number of bytes in the file, or 0 if it doesn't exist.
  96. */
  97. int64 getSize() const;
  98. /** Utility function to convert a file size in bytes to a neat string description.
  99. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  100. 2000000 would produce "2 MB", etc.
  101. */
  102. static String descriptionOfSizeInBytes (int64 bytes);
  103. //==============================================================================
  104. /** Returns the complete, absolute path of this file.
  105. This includes the filename and all its parent folders. On Windows it'll
  106. also include the drive letter prefix; on Mac or Linux it'll be a complete
  107. path starting from the root folder.
  108. If you just want the file's name, you should use getFileName() or
  109. getFileNameWithoutExtension().
  110. @see getFileName, getRelativePathFrom
  111. */
  112. const String& getFullPathName() const noexcept { return fullPath; }
  113. /** Returns the last section of the pathname.
  114. Returns just the final part of the path - e.g. if the whole path
  115. is "/moose/fish/foo.txt" this will return "foo.txt".
  116. For a directory, it returns the final part of the path - e.g. for the
  117. directory "/moose/fish" it'll return "fish".
  118. If the filename begins with a dot, it'll return the whole filename, e.g. for
  119. "/moose/.fish", it'll return ".fish"
  120. @see getFullPathName, getFileNameWithoutExtension
  121. */
  122. String getFileName() const;
  123. /** Creates a relative path that refers to a file relatively to a given directory.
  124. e.g. File ("/moose/foo.txt").getRelativePathFrom (File ("/moose/fish/haddock"))
  125. would return "../../foo.txt".
  126. If it's not possible to navigate from one file to the other, an absolute
  127. path is returned. If the paths are invalid, an empty string may also be
  128. returned.
  129. @param directoryToBeRelativeTo the directory which the resultant string will
  130. be relative to. If this is actually a file rather than
  131. a directory, its parent directory will be used instead.
  132. If it doesn't exist, it's assumed to be a directory.
  133. @see getChildFile, isAbsolutePath
  134. */
  135. String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  136. //==============================================================================
  137. /** Returns the file's extension.
  138. Returns the file extension of this file, also including the dot.
  139. e.g. "/moose/fish/foo.txt" would return ".txt"
  140. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  141. */
  142. String getFileExtension() const;
  143. /** Checks whether the file has a given extension.
  144. @param extensionToTest the extension to look for - it doesn't matter whether or
  145. not this string has a dot at the start, so ".wav" and "wav"
  146. will have the same effect. To compare with multiple extensions, this
  147. parameter can contain multiple strings, separated by semi-colons -
  148. so, for example: hasFileExtension (".jpeg;png;gif") would return
  149. true if the file has any of those three extensions.
  150. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  151. */
  152. bool hasFileExtension (StringRef extensionToTest) const;
  153. /** Returns a version of this file with a different file extension.
  154. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  155. @param newExtension the new extension, either with or without a dot at the start (this
  156. doesn't make any difference). To get remove a file's extension altogether,
  157. pass an empty string into this function.
  158. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  159. */
  160. File withFileExtension (StringRef newExtension) const;
  161. /** Returns the last part of the filename, without its file extension.
  162. e.g. for "/moose/fish/foo.txt" this will return "foo".
  163. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  164. */
  165. String getFileNameWithoutExtension() const;
  166. //==============================================================================
  167. /** Returns a file that represents a relative (or absolute) sub-path of the current one.
  168. This will find a child file or directory of the current object.
  169. e.g.
  170. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  171. File ("/moose/fish").getChildFile ("haddock/foo.txt") will produce "/moose/fish/haddock/foo.txt".
  172. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  173. If the string is actually an absolute path, it will be treated as such, e.g.
  174. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  175. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  176. */
  177. File getChildFile (StringRef relativeOrAbsolutePath) const;
  178. /** Returns a file which is in the same directory as this one.
  179. This is equivalent to getParentDirectory().getChildFile (name).
  180. @see getChildFile, getParentDirectory
  181. */
  182. File getSiblingFile (StringRef siblingFileName) const;
  183. //==============================================================================
  184. /** Returns the directory that contains this file or directory.
  185. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  186. */
  187. File getParentDirectory() const;
  188. /** Checks whether a file is somewhere inside a directory.
  189. Returns true if this file is somewhere inside a subdirectory of the directory
  190. that is passed in. Neither file actually has to exist, because the function
  191. just checks the paths for similarities.
  192. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  193. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  194. */
  195. bool isAChildOf (const File& potentialParentDirectory) const;
  196. //==============================================================================
  197. /** Chooses a filename relative to this one that doesn't already exist.
  198. If this file is a directory, this will return a child file of this
  199. directory that doesn't exist, by adding numbers to a prefix and suffix until
  200. it finds one that isn't already there.
  201. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  202. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  203. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  204. @param prefix the string to use for the filename before the number
  205. @param suffix the string to add to the filename after the number
  206. @param putNumbersInBrackets if true, this will create filenames in the
  207. format "prefix(number)suffix", if false, it will leave the
  208. brackets out.
  209. */
  210. File getNonexistentChildFile (const String& prefix,
  211. const String& suffix,
  212. bool putNumbersInBrackets = true) const;
  213. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  214. If this file doesn't exist, this will just return itself, otherwise it
  215. will return an appropriate sibling that doesn't exist, e.g. if a file
  216. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  217. @param putNumbersInBrackets whether to add brackets around the numbers that
  218. get appended to the new filename.
  219. */
  220. File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  221. //==============================================================================
  222. /** Compares the pathnames for two files. */
  223. bool operator== (const File&) const;
  224. /** Compares the pathnames for two files. */
  225. bool operator!= (const File&) const;
  226. /** Compares the pathnames for two files. */
  227. bool operator< (const File&) const;
  228. /** Compares the pathnames for two files. */
  229. bool operator> (const File&) const;
  230. //==============================================================================
  231. /** Checks whether a file can be created or written to.
  232. @returns true if it's possible to create and write to this file. If the file
  233. doesn't already exist, this will check its parent directory to
  234. see if writing is allowed.
  235. @see setReadOnly
  236. */
  237. bool hasWriteAccess() const;
  238. /** Changes the write-permission of a file or directory.
  239. @param shouldBeReadOnly whether to add or remove write-permission
  240. @param applyRecursively if the file is a directory and this is true, it will
  241. recurse through all the subfolders changing the permissions
  242. of all files
  243. @returns true if it manages to change the file's permissions.
  244. @see hasWriteAccess
  245. */
  246. bool setReadOnly (bool shouldBeReadOnly,
  247. bool applyRecursively = false) const;
  248. /** Changes the execute-permissions of a file.
  249. @param shouldBeExecutable whether to add or remove execute-permission
  250. @returns true if it manages to change the file's permissions.
  251. */
  252. bool setExecutePermission (bool shouldBeExecutable) const;
  253. /** Returns true if this file is a hidden or system file.
  254. The criteria for deciding whether a file is hidden are platform-dependent.
  255. */
  256. bool isHidden() const;
  257. /** Returns a unique identifier for the file, if one is available.
  258. Depending on the OS and file-system, this may be a unix inode number or
  259. a win32 file identifier, or 0 if it fails to find one. The number will
  260. be unique on the filesystem, but not globally.
  261. */
  262. uint64 getFileIdentifier() const;
  263. /** If possible, this will try to create a version string for the given file.
  264. The OS may be able to look at the file and give a version for it - e.g. with
  265. executables, bundles, dlls, etc. If no version is available, this will
  266. return an empty string.
  267. */
  268. String getVersion() const;
  269. //==============================================================================
  270. /** Creates an empty file if it doesn't already exist.
  271. If the file that this object refers to doesn't exist, this will create a file
  272. of zero size.
  273. If it already exists or is a directory, this method will do nothing.
  274. If the parent directories of the File do not exist then this method will
  275. recursively create the parent directories.
  276. @returns a result to indicate whether the file was created successfully,
  277. or an error message if it failed.
  278. @see createDirectory
  279. */
  280. Result create() const;
  281. /** Creates a new directory for this filename.
  282. This will try to create the file as a directory, and will also create
  283. any parent directories it needs in order to complete the operation.
  284. @returns a result to indicate whether the directory was created successfully, or
  285. an error message if it failed.
  286. @see create
  287. */
  288. Result createDirectory() const;
  289. /** Deletes a file.
  290. If this file is actually a directory, it may not be deleted correctly if it
  291. contains files. See deleteRecursively() as a better way of deleting directories.
  292. @returns true if the file has been successfully deleted (or if it didn't exist to
  293. begin with).
  294. @see deleteRecursively
  295. */
  296. bool deleteFile() const;
  297. /** Deletes a file or directory and all its subdirectories.
  298. If this file is a directory, this will try to delete it and all its subfolders. If
  299. it's just a file, it will just try to delete the file.
  300. @returns true if the file and all its subfolders have been successfully deleted
  301. (or if it didn't exist to begin with).
  302. @see deleteFile
  303. */
  304. bool deleteRecursively() const;
  305. /** Moves or renames a file.
  306. Tries to move a file to a different location.
  307. If the target file already exists, this will attempt to delete it first, and
  308. will fail if this can't be done.
  309. Note that the destination file isn't the directory to put it in, it's the actual
  310. filename that you want the new file to have.
  311. Also note that on some OSes (e.g. Windows), moving files between different
  312. volumes may not be possible.
  313. @returns true if the operation succeeds
  314. */
  315. bool moveFileTo (const File& targetLocation) const;
  316. /** Copies a file.
  317. Tries to copy a file to a different location.
  318. If the target file already exists, this will attempt to delete it first, and
  319. will fail if this can't be done.
  320. @returns true if the operation succeeds
  321. */
  322. bool copyFileTo (const File& targetLocation) const;
  323. /** Replaces a file.
  324. Replace the file in the given location, assuming the replaced files identity.
  325. Depending on the file system this will preserve file attributes such as
  326. creation date, short file name, etc.
  327. If replacement succeeds the original file is deleted.
  328. @returns true if the operation succeeds
  329. */
  330. bool replaceFileIn (const File& targetLocation) const;
  331. /** Copies a directory.
  332. Tries to copy an entire directory, recursively.
  333. If this file isn't a directory or if any target files can't be created, this
  334. will return false.
  335. @param newDirectory the directory that this one should be copied to. Note that this
  336. is the name of the actual directory to create, not the directory
  337. into which the new one should be placed, so there must be enough
  338. write privileges to create it if it doesn't exist. Any files inside
  339. it will be overwritten by similarly named ones that are copied.
  340. */
  341. bool copyDirectoryTo (const File& newDirectory) const;
  342. //==============================================================================
  343. /** Used in file searching, to specify whether to return files, directories, or both.
  344. */
  345. enum TypesOfFileToFind
  346. {
  347. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  348. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  349. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  350. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  351. };
  352. /** Searches inside a directory for files matching a wildcard pattern.
  353. Assuming that this file is a directory, this method will search it
  354. for either files or subdirectories whose names match a filename pattern.
  355. @param results an array to which File objects will be added for the
  356. files that the search comes up with
  357. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  358. return files, directories, or both. If the ignoreHiddenFiles flag
  359. is also added to this value, hidden files won't be returned
  360. @param searchRecursively if true, all subdirectories will be recursed into to do
  361. an exhaustive search
  362. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  363. @returns the number of results that have been found
  364. @see getNumberOfChildFiles, DirectoryIterator
  365. */
  366. uint findChildFiles (std::vector<File>& results,
  367. int whatToLookFor,
  368. bool searchRecursively,
  369. const String& wildCardPattern = "*") const;
  370. /** Searches inside a directory and counts how many files match a wildcard pattern.
  371. Assuming that this file is a directory, this method will search it
  372. for either files or subdirectories whose names match a filename pattern,
  373. and will return the number of matches found.
  374. This isn't a recursive call, and will only search this directory, not
  375. its children.
  376. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  377. count files, directories, or both. If the ignoreHiddenFiles flag
  378. is also added to this value, hidden files won't be counted
  379. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  380. @returns the number of matches found
  381. @see findChildFiles, DirectoryIterator
  382. */
  383. uint getNumberOfChildFiles (int whatToLookFor,
  384. const String& wildCardPattern = "*") const;
  385. /** Returns true if this file is a directory that contains one or more subdirectories.
  386. @see isDirectory, findChildFiles
  387. */
  388. bool containsSubDirectories() const;
  389. //==============================================================================
  390. /** Creates a stream to read from this file.
  391. @returns a stream that will read from this file (initially positioned at the
  392. start of the file), or nullptr if the file can't be opened for some reason
  393. @see createOutputStream, loadFileAsData
  394. */
  395. FileInputStream* createInputStream() const;
  396. /** Creates a stream to write to this file.
  397. If the file exists, the stream that is returned will be positioned ready for
  398. writing at the end of the file, so you might want to use deleteFile() first
  399. to write to an empty file.
  400. @returns a stream that will write to this file (initially positioned at the
  401. end of the file), or nullptr if the file can't be opened for some reason
  402. @see createInputStream, appendData, appendText
  403. */
  404. FileOutputStream* createOutputStream (size_t bufferSize = 0x8000) const;
  405. //==============================================================================
  406. /** Loads a file's contents into memory as a block of binary data.
  407. Of course, trying to load a very large file into memory will blow up, so
  408. it's better to check first.
  409. @param result the data block to which the file's contents should be appended - note
  410. that if the memory block might already contain some data, you
  411. might want to clear it first
  412. @returns true if the file could all be read into memory
  413. */
  414. bool loadFileAsData (MemoryBlock& result) const;
  415. /** Reads a file into memory as a string.
  416. Attempts to load the entire file as a zero-terminated string.
  417. This makes use of InputStream::readEntireStreamAsString, which can
  418. read either UTF-16 or UTF-8 file formats.
  419. */
  420. String loadFileAsString() const;
  421. /** Reads the contents of this file as text and splits it into lines, which are
  422. appended to the given StringArray.
  423. */
  424. void readLines (StringArray& destLines) const;
  425. //==============================================================================
  426. /** Appends a block of binary data to the end of the file.
  427. This will try to write the given buffer to the end of the file.
  428. @returns false if it can't write to the file for some reason
  429. */
  430. bool appendData (const void* dataToAppend,
  431. size_t numberOfBytes) const;
  432. /** Replaces this file's contents with a given block of data.
  433. This will delete the file and replace it with the given data.
  434. A nice feature of this method is that it's safe - instead of deleting
  435. the file first and then re-writing it, it creates a new temporary file,
  436. writes the data to that, and then moves the new file to replace the existing
  437. file. This means that if the power gets pulled out or something crashes,
  438. you're a lot less likely to end up with a corrupted or unfinished file..
  439. Returns true if the operation succeeds, or false if it fails.
  440. @see appendText
  441. */
  442. bool replaceWithData (const void* dataToWrite,
  443. size_t numberOfBytes) const;
  444. /** Appends a string to the end of the file.
  445. This will try to append a text string to the file, as either 16-bit unicode
  446. or 8-bit characters in the default system encoding.
  447. It can also write the 'ff fe' unicode header bytes before the text to indicate
  448. the endianness of the file.
  449. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  450. @see replaceWithText
  451. */
  452. bool appendText (const String& textToAppend,
  453. bool asUnicode = false,
  454. bool writeUnicodeHeaderBytes = false) const;
  455. /** Replaces this file's contents with a given text string.
  456. This will delete the file and replace it with the given text.
  457. A nice feature of this method is that it's safe - instead of deleting
  458. the file first and then re-writing it, it creates a new temporary file,
  459. writes the text to that, and then moves the new file to replace the existing
  460. file. This means that if the power gets pulled out or something crashes,
  461. you're a lot less likely to end up with an empty file..
  462. For an explanation of the parameters here, see the appendText() method.
  463. Returns true if the operation succeeds, or false if it fails.
  464. @see appendText
  465. */
  466. bool replaceWithText (const String& textToWrite,
  467. bool asUnicode = false,
  468. bool writeUnicodeHeaderBytes = false) const;
  469. /** Attempts to scan the contents of this file and compare it to another file, returning
  470. true if this is possible and they match byte-for-byte.
  471. */
  472. bool hasIdenticalContentTo (const File& other) const;
  473. //==============================================================================
  474. /** A set of types of location that can be passed to the getSpecialLocation() method.
  475. */
  476. enum SpecialLocationType
  477. {
  478. /** The user's home folder. This is the same as using File ("~"). */
  479. userHomeDirectory,
  480. /** The folder that should be used for temporary files.
  481. Always delete them when you're finished, to keep the user's computer tidy!
  482. */
  483. tempDirectory,
  484. /** Returns this application's executable file.
  485. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  486. host app.
  487. On the mac this will return the unix binary, not the package folder.
  488. */
  489. currentExecutableFile,
  490. /** In a plugin, this will return the path of the host executable. */
  491. hostApplicationPath,
  492. /** Windows specific paths */
  493. winAppData, winProgramFiles
  494. };
  495. /** Finds the location of a special type of file or directory, such as a home folder or
  496. documents folder.
  497. @see SpecialLocationType
  498. */
  499. static File getSpecialLocation (const SpecialLocationType type);
  500. //==============================================================================
  501. /** Returns a temporary file in the system's temp directory.
  502. This will try to return the name of a non-existent temp file.
  503. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  504. */
  505. static File createTempFile (StringRef fileNameEnding);
  506. //==============================================================================
  507. /** Returns the current working directory.
  508. @see setAsCurrentWorkingDirectory
  509. */
  510. static File getCurrentWorkingDirectory();
  511. /** Sets the current working directory to be this file.
  512. For this to work the file must point to a valid directory.
  513. @returns true if the current directory has been changed.
  514. @see getCurrentWorkingDirectory
  515. */
  516. bool setAsCurrentWorkingDirectory() const;
  517. //==============================================================================
  518. /** The system-specific file separator character.
  519. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  520. */
  521. static const water_uchar separator;
  522. /** The system-specific file separator character, as a string.
  523. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  524. */
  525. static const String separatorString;
  526. //==============================================================================
  527. /** Returns a version of a filename with any illegal characters removed.
  528. This will return a copy of the given string after removing characters
  529. that are not allowed in a legal filename, and possibly shortening the
  530. string if it's too long.
  531. Because this will remove slashes, don't use it on an absolute pathname - use
  532. createLegalPathName() for that.
  533. @see createLegalPathName
  534. */
  535. static String createLegalFileName (const String& fileNameToFix);
  536. /** Returns a version of a path with any illegal characters removed.
  537. Similar to createLegalFileName(), but this won't remove slashes, so can
  538. be used on a complete pathname.
  539. @see createLegalFileName
  540. */
  541. static String createLegalPathName (const String& pathNameToFix);
  542. /** Indicates whether filenames are case-sensitive on the current operating system. */
  543. static bool areFileNamesCaseSensitive();
  544. /** Returns true if the string seems to be a fully-specified absolute path. */
  545. static bool isAbsolutePath (StringRef path);
  546. /** Creates a file that simply contains this string, without doing the sanity-checking
  547. that the normal constructors do.
  548. Best to avoid this unless you really know what you're doing.
  549. */
  550. static File createFileWithoutCheckingPath (const String& absolutePath) noexcept;
  551. /** Adds a separator character to the end of a path if it doesn't already have one. */
  552. static String addTrailingSeparator (const String& path);
  553. //==============================================================================
  554. /** Tries to create a symbolic link and returns a boolean to indicate success */
  555. bool createSymbolicLink (const File& linkFileToCreate, bool overwriteExisting) const;
  556. /** Returns true if this file is a link or alias that can be followed using getLinkedTarget(). */
  557. bool isSymbolicLink() const;
  558. /** If this file is a link or alias, this returns the file that it points to.
  559. If the file isn't actually link, it'll just return itself.
  560. */
  561. File getLinkedTarget() const;
  562. //==============================================================================
  563. struct NaturalFileComparator
  564. {
  565. NaturalFileComparator (bool shouldPutFoldersFirst) noexcept : foldersFirst (shouldPutFoldersFirst) {}
  566. int compareElements (const File& firstFile, const File& secondFile) const
  567. {
  568. if (foldersFirst && (firstFile.isDirectory() != secondFile.isDirectory()))
  569. return firstFile.isDirectory() ? -1 : 1;
  570. return firstFile.getFullPathName().compareNatural (secondFile.getFullPathName(), File::areFileNamesCaseSensitive());
  571. }
  572. bool foldersFirst;
  573. };
  574. private:
  575. //==============================================================================
  576. String fullPath;
  577. static String parseAbsolutePath (const String&);
  578. String getPathUpToLastSlash() const;
  579. Result createDirectoryInternal (const String&) const;
  580. bool copyInternal (const File&) const;
  581. bool moveInternal (const File&) const;
  582. bool replaceInternal (const File&) const;
  583. bool setFileTimesInternal (int64 m, int64 a, int64 c) const;
  584. void getFileTimesInternal (int64& m, int64& a, int64& c) const;
  585. bool setFileReadOnlyInternal (bool) const;
  586. bool setFileExecutableInternal (bool) const;
  587. };
  588. }
  589. #endif // WATER_FILE_H_INCLUDED