ImFusion SDK 4.3
Filesystem Library

Lightweight filesystem library. More...

+ Collaboration diagram for Filesystem Library:

Detailed Description

Lightweight filesystem library.

This library provides an easy to use abstraction layer for accessing the local filesystem so that you do not need to fall back to OS-specific APIs or third party libraries. Its design is somewhat similar to std::filesystem however it provides some additional convenience functionality; furthermore, individual functions may behave differently than its counterparts in the standard library.

Note
Just as the rest of the ImFusion SDK ImFusion::Filesystem expects and uses UTF-8 encoding in its interface (e.g when passing folder/file names). Any potentially required conversion to a platform-specific encoding such as UTF-16 on Windows is handled internally

General structure

The filesystem library consists of four classes as well as a set of free functions all residing in the ImFusion::Filesystem namespace:

Usage Examples

Internally the path is represented as a string. One can initialize a path object either with '/' (generic format) or '\' (Windows native), however it gets converted to the generic format with forward slashes '/' and all the member functions output paths in the generic format.

std::string nativePathAsString = "C:\Program Files\ImFusion Suite";
Filesystem::Path fsPath = nativePathAsString; // will convert native path separators to generic ones
LOG_INFO(fsPath.parentPath()); // logs "C:/Program Files"
IMFUSION_ASSERT(std::string(fsPath) == "C:/Program Files/ImFusion Suite");

A path can be a path to a directory or a file. It can be absolute or relative. It can be decomposed into individual parts such as parent path, filename, (full) base name, (full) extension.

Filesystem::File file{"/home/username/Data/zipfile.tar.gz"};
std::cout << "Parent Path: " << file.parentPath() << std::endl; // -> "/home/username/Data"
std::cout << "Name: " << file.name() << std::endl; // -> "zipfile.tar.gz"
std::cout << "Basename: " << file.path().baseName() << std::endl; // -> "zipfile"
std::cout << "Full Basename: " << file.path().fullBaseName() << std::endl; // -> "zipfile.tar"
std::cout << "Extension: " << file.path().extension() << std::endl; // -> "gz"
std::cout << "Full Extension: " << file.path().fullExtension() << std::endl; // -> "tar.gz"

One can create a canonical path, which resolves all symbolic links, cleans the path from '.' and '..'. One can also create a relative to a given directory path.

Filesystem::Path dataDirectoryPath =
Filesystem::Path{"/home/username/Development/./Data/symbolic_link_image.imf"}.makeCanonical();
// => dataDirectoryPath == "/data/real_image.imf"
Filesystem::Path relativePath = dataDirectoryPath.makeRelativeTo("/data");
// => relativePath == "real_image.imf"

Paths can be compared with the operators == and !=, as well as concatenated with the operator /.

Filesystem::Path projectDirectoryPath{"/home/username/Development"};
Filesystem::Path dataDirectoryPath = projectDirectoryPath / "data"; // "/home/username/Development/data"
Filesystem::Path testDataPath = projectDirectoryPath / Path("test"); // "/home/username/Development/data/test"
IMFUSION_ASSERT(projectDirectoryPath != testDataPath);

In order to run actual operations on the underlying filesystem you should use the File and/or Directory classes. There are convenience functions to easily derive them from a Path.

Filesystem::Path savePath{"/home/username/data/project/my file.bin"};
savePath.asDirectory().createRecursive(); // make sure the parent directory actually exists
savePath.asFile().writeBinary(data); // create the file and write data to it

Namespaces

namespace  ImFusion::Filesystem
 Classes and functions to manipulate files and directories, and the paths that identify them.
 

Classes

class  File
 Entity representing a file in the filesystem. More...
 
class  Directory
 Entity representing a Directory in the filesystem. More...
 
class  Path
 Entity representing a path in the filesystem. More...
 
class  TemporaryFile
 Temporary file which deletes itself upon going out of scope. More...
 
class  TemporaryDirectory
 Temporary directory which deletes itself upon going out of scope. More...
 
class  Url
 Entity representing a URL (Uniform Resource Locator). More...
 

Enumerations

enum class  CopyOptions {
  None = 0 , SkipExistingFiles = 1 << 0 , OverwriteExistingFiles = 1 << 1 , Recursive = 1 << 3 ,
  DirectoriesOnly = 1 << 4
}
 Bitflag enumeration to configure calls to copy(). More...
 

Functions

Path currentWorkingDirectory ()
 Returns the current working directory.
 
bool setCurrentWorkingDirectory (const Path &path)
 Sets the current working directory.
 
Path tempDirectory ()
 Returns the location of the directory for temporary files for the current platform.
 
Path homeDirectory ()
 Returns the location of the "home" directory if possible, otherwise returns an empty Path object and logs an error message.
 
Path configDirectory ()
 Returns the location of the directory for configuration files for the current platform.
 
Path randomPath (const Path &model="%%%%-%%%%-%%%%-%%%%")
 Generates a random path based on the provided model, where it replaces each percent sign character by a random hexadecimal digit.
 
Path commonParentDirectory (const std::vector< Path > &filepaths)
 Returns the most common parent directory of all given files.
 
bool isPortableFilename (const std::string &filename)
 Checks whether the given string forms a valid filename on common environments such as POSIX and Windows.
 
std::string makePortableFilename (const std::string &filename, char replacementCharacter='_')
 Checks the given string for any characters that would be invalid on common environments such as POSIX and Windows and replaces them with the provided replacementCharacter.
 
Path removeTrailingSlash (const Path &path)
 Returns a Path with no trailing path separators (On Windows '\' as well as POSIX '/' will be considered).
 
bool copy (const Path &source, const Path &destination, Flags< CopyOptions > copyOptions=CopyOptions::None, std::function< bool(const Path &sourcePath)> filter=nullptr)
 Copies files and/or directories from source to destination based on the provided options and optional filter.
 
bool rename (const Path &from, const Path &to)
 Rename the given file/directory.
 
bool createDirectories (const Path &path)
 Recursively creates the directories in the given path in case they do not exist yet.
 
bool remove (const Path &path)
 Non-recursively deletes the given file/directory.
 
bool removeRecursive (const Path &path)
 Recursively deletes the given file/directory and all of its contents.
 

Enumeration Type Documentation

◆ CopyOptions

enum class CopyOptions
strong

#include <ImFusion/Core/Filesystem/Filesystem.h>

Bitflag enumeration to configure calls to copy().

Enumerator
None 

Copy files and directories, non-recursively, abort if file already exists.

SkipExistingFiles 

Keep already existing files without reporting an error.

OverwriteExistingFiles 

Replace already existing files without reporting an error.

Recursive 

Recursively copy subdirectories and their content.

DirectoriesOnly 

Copy the directory structure but nothing else.

Function Documentation

◆ currentWorkingDirectory()

Path currentWorkingDirectory ( )

#include <ImFusion/Core/Filesystem/Filesystem.h>

Returns the current working directory.

Note
This function returns global state.

◆ setCurrentWorkingDirectory()

bool setCurrentWorkingDirectory ( const Path & path)

#include <ImFusion/Core/Filesystem/Filesystem.h>

Sets the current working directory.

Note
This function modifies global state.

◆ homeDirectory()

Path homeDirectory ( )

#include <ImFusion/Core/Filesystem/Filesystem.h>

Returns the location of the "home" directory if possible, otherwise returns an empty Path object and logs an error message.

To locate the home directory, the following environment variables are retrieved in order and returned if non-empty:

  1. Windows only: USERPROFILE
  2. Windows only: HOMEDRIVE + HOMEPATH
  3. Windows and Unix: HOME

◆ configDirectory()

Path configDirectory ( )

#include <ImFusion/Core/Filesystem/Filesystem.h>

Returns the location of the directory for configuration files for the current platform.

  • Windows: APPDATA%/
  • Linux: $HOME/.config/
  • Mac: $HOME/Library/Preferences/

◆ randomPath()

Path randomPath ( const Path & model = "%%%%-%%%%-%%%%-%%%%")

#include <ImFusion/Core/Filesystem/Filesystem.h>

Generates a random path based on the provided model, where it replaces each percent sign character by a random hexadecimal digit.

The default model is of the form %%%%-%%%%-%%%%-%%%%, providing 64 bits of randomness which should be sufficient for most applications such as creating temporary files or directories.

Note
If you provide a model without percent sign characters, the untouched input path will be returned.

◆ commonParentDirectory()

Path commonParentDirectory ( const std::vector< Path > & filepaths)

#include <ImFusion/Core/Filesystem/Filesystem.h>

Returns the most common parent directory of all given files.

If no common directory could be determined, an empty string is returned. All paths in filepaths will be normalized before determining the common parent directory, therefore also the result will be in normalized form (cf. Path::makeNormalized()).

◆ removeTrailingSlash()

Path removeTrailingSlash ( const Path & path)

#include <ImFusion/Core/Filesystem/Filesystem.h>

Returns a Path with no trailing path separators (On Windows '\' as well as POSIX '/' will be considered).

removeTrailingSlash("./directory1/"); -> "./directory1"
removeTrailingSlash("./directory1////"); -> "./directory1"
removeTrailingSlash("./directory1/directory2"); -> "./directory1/directory2"
removeTrailingSlash("./directory1/myfile.pdf"); -> "./directory1/myfile.pdf"
removeTrailingSlash("/"); -> "/"
removeTrailingSlash("./"); -> "."
removeTrailingSlash("../"); -> ".."
Path removeTrailingSlash(const Path &path)
Returns a Path with no trailing path separators (On Windows '\' as well as POSIX '/' will be consider...

◆ copy()

bool copy ( const Path & source,
const Path & destination,
Flags< CopyOptions > copyOptions = CopyOptions::None,
std::function< bool(const Path &sourcePath)> filter = nullptr )

#include <ImFusion/Core/Filesystem/Filesystem.h>

Copies files and/or directories from source to destination based on the provided options and optional filter.

This is a convenience function for

if (source.isFile())
return source.asFile().copyTo(destination, copyOptions);
else if (source.isDirectory())
return source.asDirectory().copyTo(destination, copyOptions, filter);
Parameters
sourceSource file or directory to copy.
destinationTarget name of the file or directory to copy. If source describes a file and destination an existing directory, then behaves as copy(source, destination / source.filename(), ...).
copyOptionsOptional flags to control the behavior of this function.
filterOptional filter function, if provided will copy only those elements where it returns true; copy() will call the filter function for every element to copy providing its absolute path.

◆ rename()

bool rename ( const Path & from,
const Path & to )

#include <ImFusion/Core/Filesystem/Filesystem.h>

Rename the given file/directory.

This is a convenience function for

if (source.isFile())
return source.asFile().rename(to);
else if (source.isDirectory())
return source.asDirectory().rename(to);
Parameters
fromOriginal path to the file/directory to be renamed.
toNew path of the file/directory to be renamed.

◆ createDirectories()

bool createDirectories ( const Path & path)

#include <ImFusion/Core/Filesystem/Filesystem.h>

Recursively creates the directories in the given path in case they do not exist yet.

This function has the same effect as path.asDirectory().createRecursive(). If path resolves to an already existing directory, no error is reported.

Parameters
pathDirectory structure to create.

◆ remove()

bool remove ( const Path & path)

#include <ImFusion/Core/Filesystem/Filesystem.h>

Non-recursively deletes the given file/directory.

Fails if path is a non-empty directory. If the path is a symbolic link, it removes only the link. If the path did not exist in the first place, does nothing and returns true.

Parameters
pathPath to file/directory to delete.

◆ removeRecursive()

bool removeRecursive ( const Path & path)

#include <ImFusion/Core/Filesystem/Filesystem.h>

Recursively deletes the given file/directory and all of its contents.

If the path is a symbolic link, it removes only the link. If the path did not exist in the first place, does nothing and returns true.

Parameters
pathPath to file/directory to delete.
Search Tab / S to search, Esc to close