lfilesystem  0.0.1
C++ filesystem library
limes::files::File Class Reference

This class represents a file on the filesystem. More...

#include <lfilesystem_File.h>

+ Inheritance diagram for limes::files::File:

Classes

struct  Iterator
 An iterator class that allows iterating a file like a standard C++ container. More...
 

Public Member Functions

 File (const File &)=default
 
 File (File &&)=default
 
Iterator begin () const
 Returns an iterator to the first line in this file. More...
 
std::optional< Fileduplicate () const noexcept
 Duplicates this file within its directory. More...
 
Iterator end () const
 Returns an iterator to the last line in this file. More...
 
 FilesystemEntry ()=default
 Creates a FilesystemEntry with an empty path. More...
 
 FilesystemEntry (const FilesystemEntry &)=default
 
 FilesystemEntry (const Path &pathToUse)
 Creates a FilesystemEntry referring to the specified path. More...
 
 FilesystemEntry (FilesystemEntry &&)=default
 
CFile getCfile (CFile::Mode mode=CFile::Mode::Read) const noexcept
 Returns a CFile referring to this filepath. More...
 
Fileoperator= (const File &)=default
 
Fileoperator= (File &&)=default
 
bool resize (std::uintmax_t newSizeInBytes, bool allowTruncation=true, bool allowIncreasing=true) const noexcept
 Resizes this file to the set number of bytes. More...
 
Path queries
std::string getFilename (bool includeExtension=false) const
 Returns this file's filename. More...
 
std::string getFileExtension () const
 Returns this file's file extension, if any. More...
 
bool hasFileExtension (const std::string_view &extension) const
 Returns true if this file has the specified file extension. More...
 
bool hasFileExtension () const
 Returns true if this file has a file extension. More...
 
bool isMacOSBundle () const noexcept
 Returns true if this file is a MacOS bundle. More...
 
bool isFile () const noexcept final
 Returns this file's filename. More...
 
bool isDirectory () const noexcept final
 Returns this file's filename. More...
 
bool isSymLink () const noexcept final
 Returns this file's filename. More...
 
Path manipulation
bool replaceFileExtension (const std::string_view &newFileExtension, bool renameOnDisk=true)
 Replaces the file extension of this file. More...
 
Fileoperator= (const Path &newPath)
 Assigns this object to refer to a new path. More...
 
Fileoperator= (const std::string_view &newPath)
 Assigns this object to refer to a new path. More...
 
Loading the file
std::string loadAsString () const noexcept
 Loads the file's contents as a string. More...
 
std::vector< std::string > loadAsLines () const
 Loads the file's contents as a vector of strings, with each string containing the contents of one line of the file. More...
 
std::unique_ptr< std::ifstream > getInputStream () const
 Returns a standard input stream for reading from this file. More...
 
Overwriting with content
bool overwrite (const char *const data, std::size_t numBytes) const noexcept
 Replaces the file's contents with the given data. More...
 
bool overwrite (const std::string_view &text) const noexcept
 Replaces the file's contents with the given data. More...
 
std::unique_ptr< std::ofstream > getOutputStream () const
 Returns a standard output stream for writing to this file. More...
 
Appending content
bool append (const char *const data, std::size_t numBytes) const noexcept
 Appends the given data to the file's current contents. More...
 
bool append (const std::string_view &text) const noexcept
 Appends the given data to the file's current contents. More...
 
Prepending content
bool prepend (const char *const data, std::size_t numBytes) const noexcept
 Prepends the given data to the file's current contents. More...
 
bool prepend (const std::string_view &text) const noexcept
 Prepends the given data to the file's current contents. More...
 
Hard links
std::optional< FilecreateHardLink (const Path &path) const
 Creates a hard link to this file at the specified path . More...
 
std::uintmax_t getHardLinkCount () const noexcept
 Returns the number of hard links referring to this underlying filesystem object. More...
 
- Public Member Functions inherited from limes::files::FilesystemEntry
 FilesystemEntry (const FilesystemEntry &)=default
 
 FilesystemEntry (FilesystemEntry &&)=default
 
virtual ~FilesystemEntry ()=default
 Destructor. More...
 
bool copyFrom (const FilesystemEntry &source, CopyOptions options=CopyOptions::update_existing) const noexcept
 
bool copyFrom (const Path &source, CopyOptions options=CopyOptions::update_existing) const noexcept
 Overwriting. More...
 
FilesystemEntryoperator= (const FilesystemEntry &)=default
 
FilesystemEntryoperator= (FilesystemEntry &&)=default
 
bool revealToUserInFileBrowser () const
 Uses the system's native file browser to display this file to the user. More...
 
 FilesystemEntry ()=default
 Creates a FilesystemEntry with an empty path. More...
 
 FilesystemEntry (const Path &pathToUse)
 Creates a FilesystemEntry referring to the specified path. More...
 
FilesystemEntryoperator= (const Path &newPath)
 Assigns the path this filesystem entry represents. More...
 
FilesystemEntryoperator= (const std::string_view &newPath)
 Assigns the path this filesystem entry represents. More...
 
FilesystemEntryassignPath (const Path &newPath) noexcept
 Assigns the path this filesystem entry represents. More...
 
bool operator== (const FilesystemEntry &other) const noexcept
 Compares this filesystem entry's absolute path with the other one's for equality. More...
 
bool operator== (const Path &other) const noexcept
 Compares this filesystem entry's absolute path with the other one's for equality. More...
 
bool operator!= (const FilesystemEntry &other) const noexcept
 Compares this filesystem entry's absolute path with the other one's for equality. More...
 
bool operator!= (const Path &other) const noexcept
 Compares this filesystem entry's absolute path with the other one's for equality. More...
 
bool operator< (const FilesystemEntry &other) const noexcept
 Lexicographically compares this filesystem entry's absolute path with another path. More...
 
bool operator> (const FilesystemEntry &other) const noexcept
 Lexicographically compares this filesystem entry's absolute path with another path. More...
 
bool operator< (const Path &other) const noexcept
 Lexicographically compares this filesystem entry's absolute path with another path. More...
 
bool operator> (const Path &other) const noexcept
 Lexicographically compares this filesystem entry's absolute path with another path. More...
 
FilesystemEntry operator/ (const std::string_view &subpathName) const
 Returns a new FilesystemEntry referring to a subpath of this one. More...
 
FilesystemEntryoperator/= (const std::string_view &subpathName)
 Assigns this object's path to a subpath of the current path. More...
 
FilesystemEntrychangeName (const std::string_view &newName)
 Changes the last section of the path (the filename). More...
 
bool makeAbsoluteRelativeTo (const Path &basePath) noexcept
 If the path this object holds is already absolute, this function does nothing and returns false. More...
 
bool makeAbsoluteRelativeToCWD () noexcept
 Similar to makeAbsoluteRelativeTo(), but uses the current working directory as the base path. More...
 
Path getPath (bool makePreferred=false) const noexcept
 Returns the current path held by this object. More...
 
Path getAbsolutePath (bool makePreferred=false) const noexcept
 Returns the full, absolute path of this filesystem entry. More...
 
 operator Path () const noexcept
 Converts this filesystem entry to the path it holds. More...
 
std::string getName () const noexcept
 Returns the last section of the path (the filename). More...
 
Directory getDirectory () const
 Returns the directory containing this filesystem entry. More...
 
Directory getParentDirectory () const
 Returns the parent directory of this filesystem entry. More...
 
bool isBelow (const Directory &directory, std::size_t depthLimit=50) const
 Returns true if this filesystem entry is in a subdirectory of the given directory – ie, if that directory is a parent or grandparent of this filepath. More...
 
bool isAbsolutePath () const noexcept
 Returns true if the path this object holds is an absolute path. More...
 
bool isRelativePath () const noexcept
 Returns true if the path this object holds is a relative path. More...
 
bool isValid () const noexcept
 Returns true if this object holds a valid filesystem path. More...
 
bool isHidden () const
 Returns true if this path is a hidden file or directory. More...
 
FilesystemEntry getSibling (const std::string_view &siblingName) const
 Returns a filesystem entry with the given name in the same directory as this one. More...
 
bool exists () const noexcept
 Returns true if the filesystem object this object refers to exists on disk. More...
 
 operator bool () const noexcept
 Returns true if this filesystem object exists. More...
 
virtual std::uintmax_t sizeInBytes () const
 Returns the size, in bytes, of the filesystem entry referred to by this object. More...
 
Time getLastModificationTime () const noexcept
 Returns the last modification time of the filesystem entry. More...
 
std::optional< VolumegetVolume () const noexcept
 Returns a Volume object representing the logical filesystem volume that this object exists on. More...
 
std::optional< FilegetFileObject () const noexcept
 If this object refers to a file, constructs a File object referring to the same file. More...
 
std::optional< DirectorygetDirectoryObject () const noexcept
 If this object refers to a directory, constructs a Directory object referring to the same directory. More...
 
std::optional< SymLinkgetSymLinkObject () const noexcept
 If this object refers to a symbolic link, constructs a SymLink object referring to the same link. More...
 
virtual bool createIfDoesntExist () const noexcept
 Creates the filesystem entry this object refers to, if it doesn't already exist. More...
 
bool deleteIfExists () const noexcept
 Deletes the filesystem entry this object refers to, if it exists. More...
 
bool moveToTrash () noexcept
 Attempts to move this filesystem object to the system's trash folder. More...
 
void touch () const
 If the filesystem entry this object refers do doesn't exist, this function creates it. More...
 
bool touch_noCreate () const
 The same as touch() , except this function does not create the filesystem entry if it didn't already exist. More...
 
bool rename (const Path &newPath) noexcept
 Renames this filesystem object to a new path. More...
 
bool setPermissions (FSPerms permissions, PermOptions options=PermOptions::replace) const noexcept
 Sets the permissions for the filesystem entry. More...
 
Permissions getPermissions () const
 Returns the current permissions of the filesystem entry this object refers to. More...
 
bool copyTo (const Path &dest, CopyOptions options=CopyOptions::update_existing) const noexcept
 Creates a copy of this filesystem entry at a new location on disk. More...
 
bool copyTo (const FilesystemEntry &dest, CopyOptions options=CopyOptions::update_existing) const noexcept
 Creates a copy of this filesystem entry at a new location on disk. More...
 
std::optional< FilesystemEntrycopyToDirectory (const Path &destDirectory, CopyOptions options=CopyOptions::update_existing) const noexcept
 Creates a copy of this filesystem object, with the same filename, in a different directory. More...
 

Static Public Member Functions

static File getCurrentExecutable ()
 Returns a file representing the location of the executable file that launched the current process. More...
 
static File getCurrentModule ()
 Returns a file representing the location of the current code module. More...
 

Related Functions

(Note that these are not member functions.)

std::ostream & operator<< (std::ostream &os, const File &file)
 Writes the file's contents to the output stream. More...
 
std::istream & operator>> (std::istream &is, const File &file)
 Reads content from the input stream, and overwrites the file with it. More...
 

Additional Inherited Members

- Public Types inherited from limes::files::FilesystemEntry
using PermOptions = std::filesystem::perm_options
 Options bitfield for setting permissions. More...
 
using CopyOptions = std::filesystem::copy_options
 Options bitfield for copying. More...
 
using Time = std::filesystem::file_time_type
 A time point used for filesystem time. More...
 

Detailed Description

This class represents a file on the filesystem.

This class provides a high-level API for reading from and writing to files.

For example:

const limes::files::File file { "/my/file.txt" };
for (const auto& line : file.loadAsLines())
std::cout << line << std::endl;
file.overwrite ("New file content...");
This class represents a file on the filesystem.
bool overwrite(const char *const data, std::size_t numBytes) const noexcept
Replaces the file's contents with the given data.
See also
CFile
Todo:

start as process

get user/group ID of owner?

Examples
files_dir_enumerate.cpp, and files_dir_listen.cpp.

Definition at line 61 of file lfilesystem_File.h.

Member Function Documentation

◆ append() [1/2]

bool limes::files::File::append ( const char *const  data,
std::size_t  numBytes 
) const
noexcept

Appends the given data to the file's current contents.

For best performance, if you need to append multiple pieces of data to a file, you should prefer to load its previous content, make all your alterations, and use one of the overwrite() methods. Calling this function repeatedly is unnecessarily expensive.

Returns
True if writing the data was successful

◆ append() [2/2]

bool limes::files::File::append ( const std::string_view &  text) const
noexcept

Appends the given data to the file's current contents.

For best performance, if you need to append multiple pieces of data to a file, you should prefer to load its previous content, make all your alterations, and use one of the overwrite() methods. Calling this function repeatedly is unnecessarily expensive.

Returns
True if writing the data was successful

◆ begin()

Iterator limes::files::File::begin ( ) const

Returns an iterator to the first line in this file.

◆ createHardLink()

std::optional<File> limes::files::File::createHardLink ( const Path path) const

Creates a hard link to this file at the specified path .

The file at the new path will reference the same underlying filesystem object as this file; the two will be indistinguishable and it is not possible to tell which was the "original" file.

If a relative path is passed, it is evaluated relative to the current working directory.

Returns
A File object representing the path of the newly creating hardlink. A nullopt may be returned if creating the hardlink fails.
See also
getHardLinkCount()

◆ duplicate()

std::optional<File> limes::files::File::duplicate ( ) const
noexcept

Duplicates this file within its directory.

This creates a new file containing the same content as this file, in this file's directory, and automatically names the new file. The new file will be named <thisFileName>_copy.<thisFileXtn> , unless a file with that name already exists, in which case it will be named <thisFileName>_copy2.<thisFileXtn> , and so on, until a unique name in the current directory is reached. If no unique filename can be created using this pattern within the first 999 iterations, then a nullopt is returned.

For example:

const limes::files::File file { "/path/to/file.txt" };
const auto copy1 = file.duplicate();
// if 'path/to/file_copy.txt' did not exist:
assert (copy1->getAbsolutePath() == "path/to/file_copy.txt");
// but if it did exist:
assert (copy1->getAbsolutePath() == "path/to/file_copy2.txt");
// and if that path existed:
assert (copy1->getAbsolutePath() == "path/to/file_copy3.txt");
// etc...
std::optional< File > duplicate() const noexcept
Duplicates this file within its directory.
Returns
The new file that was created, or a nullopt if duplication fails.
Note
This always returns nullopt if the file does not exist when this function is called.
Todo:
test coverage

◆ end()

Iterator limes::files::File::end ( ) const

Returns an iterator to the last line in this file.

◆ FilesystemEntry() [1/2]

limes::files::FilesystemEntry::FilesystemEntry
default

Creates a FilesystemEntry with an empty path.

After creating a FilesystemEntry with this default constructor, calling isValid() on it will return false. You can use the assignPath() function to assign this object to a path after it has been constructed.

◆ FilesystemEntry() [2/2]

limes::files::FilesystemEntry::FilesystemEntry
explicit

Creates a FilesystemEntry referring to the specified path.

Parameters
pathToUseThe path to this filesystem entry. This can be an absolute or relative path, and it is not an error if the passed path doesn't actually exist on disk. The path will be normalized using the normalizePath() function.

◆ getCfile()

CFile limes::files::File::getCfile ( CFile::Mode  mode = CFile::Mode::Read) const
noexcept

Returns a CFile referring to this filepath.

When the CFile constructor is called, a file handle for this file will be opened. This will return an invalid CFile object if the file does not exist.

See also
CFile

◆ getCurrentExecutable()

static File limes::files::File::getCurrentExecutable ( )
static

Returns a file representing the location of the executable file that launched the current process.

If the calling code is an audio plugin, this will return the path to the DAW it's being run in.

Note
The file returned by this function may not exist anymore; on some Unixes, it is perfectly legal to delete an executable file while the executable is still running.
See also
getCurrentModule()

◆ getCurrentModule()

static File limes::files::File::getCurrentModule ( )
static

Returns a file representing the location of the current code module.

If the current process is a dynamic library, this will return the path to the library file. Otherwise, this may return the same thing as getCurrentExecutable() .

If the calling code is an audio plugin, this will return the path to the plugin binary.

See also
getCurrentExecutable()

◆ getFileExtension()

std::string limes::files::File::getFileExtension ( ) const

Returns this file's file extension, if any.

See also
getFilename()

◆ getFilename()

std::string limes::files::File::getFilename ( bool  includeExtension = false) const

Returns this file's filename.

Parameters
includeExtensionWhen true, the file extension is included in the returned string. When false, the file extension and trailing dot are omitted.
See also
getFileExtension()

◆ getHardLinkCount()

std::uintmax_t limes::files::File::getHardLinkCount ( ) const
noexcept

Returns the number of hard links referring to this underlying filesystem object.

If this file doesn't exist or an error occurs, this will return 0.

See also
createHardLink()

◆ getInputStream()

std::unique_ptr<std::ifstream> limes::files::File::getInputStream ( ) const

Returns a standard input stream for reading from this file.

See also
getOutputStream()
Todo:
test coverage

◆ getOutputStream()

std::unique_ptr<std::ofstream> limes::files::File::getOutputStream ( ) const

Returns a standard output stream for writing to this file.

See also
getInputStream()
Todo:
test coverage

◆ hasFileExtension() [1/2]

bool limes::files::File::hasFileExtension ( ) const

Returns true if this file has a file extension.

◆ hasFileExtension() [2/2]

bool limes::files::File::hasFileExtension ( const std::string_view &  extension) const

Returns true if this file has the specified file extension.

The passed file extension may contain or omit the dot; '.json' or 'json' will both give the same results.

◆ isDirectory()

bool limes::files::File::isDirectory ( ) const
finalvirtualnoexcept

Returns this file's filename.

Parameters
includeExtensionWhen true, the file extension is included in the returned string. When false, the file extension and trailing dot are omitted.
See also
getFileExtension()

Reimplemented from limes::files::FilesystemEntry.

◆ isFile()

bool limes::files::File::isFile ( ) const
finalvirtualnoexcept

Returns this file's filename.

Parameters
includeExtensionWhen true, the file extension is included in the returned string. When false, the file extension and trailing dot are omitted.
See also
getFileExtension()

Reimplemented from limes::files::FilesystemEntry.

◆ isMacOSBundle()

bool limes::files::File::isMacOSBundle ( ) const
noexcept

Returns true if this file is a MacOS bundle.

Obviously, this always returns false on non-Apple platforms. Currently, this also always returns false on iOS, since there doesn't seem to be a way to detect this without trying to open the bundle.

◆ isSymLink()

bool limes::files::File::isSymLink ( ) const
finalvirtualnoexcept

Returns this file's filename.

Parameters
includeExtensionWhen true, the file extension is included in the returned string. When false, the file extension and trailing dot are omitted.
See also
getFileExtension()

Reimplemented from limes::files::FilesystemEntry.

◆ loadAsLines()

std::vector<std::string> limes::files::File::loadAsLines ( ) const

Loads the file's contents as a vector of strings, with each string containing the contents of one line of the file.

See also
loadAsString()
Examples
files_dir_enumerate.cpp.

◆ loadAsString()

std::string limes::files::File::loadAsString ( ) const
noexcept

Loads the file's contents as a string.

See also
loadAsLines()

◆ operator=() [1/2]

File& limes::files::File::operator= ( const Path newPath)

Assigns this object to refer to a new path.

Todo:
test coverage

◆ operator=() [2/2]

File& limes::files::File::operator= ( const std::string_view &  newPath)

Assigns this object to refer to a new path.

Todo:
test coverage

◆ overwrite() [1/2]

bool limes::files::File::overwrite ( const char *const  data,
std::size_t  numBytes 
) const
noexcept

Replaces the file's contents with the given data.

Returns
True if writing the data was successful
Examples
files_dir_enumerate.cpp.

◆ overwrite() [2/2]

bool limes::files::File::overwrite ( const std::string_view &  text) const
noexcept

Replaces the file's contents with the given data.

Returns
True if writing the data was successful

◆ prepend() [1/2]

bool limes::files::File::prepend ( const char *const  data,
std::size_t  numBytes 
) const
noexcept

Prepends the given data to the file's current contents.

Returns
True if writing the data was successful

◆ prepend() [2/2]

bool limes::files::File::prepend ( const std::string_view &  text) const
noexcept

Prepends the given data to the file's current contents.

Returns
True if writing the data was successful

◆ replaceFileExtension()

bool limes::files::File::replaceFileExtension ( const std::string_view &  newFileExtension,
bool  renameOnDisk = true 
)

Replaces the file extension of this file.

This function can rename the file on disk, or only alter the internal path held by this object.

Parameters
newFileExtensionThe new file extension to use.
renameOnDiskIf true, the file is actually renamed on the filesystem. If false, this function only changes the internal representation of the path, and will always return false .
Returns
True if the file was actually renamed on disk successfully. If the renameOnDisk parameter is false, this function always returns false.
See also
FilesystemEntry::rename()
Todo:
test coverage

◆ resize()

bool limes::files::File::resize ( std::uintmax_t  newSizeInBytes,
bool  allowTruncation = true,
bool  allowIncreasing = true 
) const
noexcept

Resizes this file to the set number of bytes.

If the file was larger than this size, the extra data is discarded. If the file was smaller, the size will be increased via zero-padding. On systems that support sparse files, the allocation won't actually take place until non-zero bytes are written to this file, though the filesystem will still store the file's new size as the newly increased size.

The allowTruncation and allowIncreasing parameters can be used to make sure this function only increases or decreases the file's size, though by default it may do either. If both allowTruncation and allowIncreasing are false, an assertion will be thrown, as this doesn't make much sense.

Returns
False if this file didn't already exist, if the passed size was the same as the file's original size, or if an error occurs in resizing.

The documentation for this class was generated from the following file: