File-System Paths

Introduction

The path module provides Path as the platform-independent value type for filesystem path text and exposes components for cached metadata, file content, directory traversal, filesystem operations, and managed temporary resources. It can parse generic, POSIX, and Windows path forms, inspect path elements, edit file names and suffixes, join and slice paths, convert external formats, and perform portable filesystem work with structured diagnostics.

For the domain overview and filesystem behavior, see Path API Overview. For practical path-value examples, see Working with Paths.

Process Directories

Path::currentDirectory() returns the process working directory. Path::executablePath() returns the absolute executable image path of the current process and is a convenience wrapper around erbsland::system::ProcessInfo. Its non-throwing form returns an empty path on failure, while Path::executablePathOrThrow() translates the native system diagnostic into a PathError without discarding its native context. Path::userHomeDirectory() resolves the effective user’s configured home or profile directory through the native account system rather than an environment variable. It returns an absolute native path without creating or checking the directory. The OrThrow form reports lookup and conversion failures as PathError; the non-throwing form returns an empty path. Path::systemTempDirectory() resolves the platform temporary directory.

File Locks

Path::createLock() acquires a nonblocking exclusive process lock and returns a move-only FileLock owner. The operating-system lock is held on a persistent .lock sidecar file, so you can replace the protected path atomically without dropping mutual exclusion. The sidecar remains after release to avoid races between lock users, and existing sidecar content is preserved. Acquisition reports an invalid path, an inaccessible sidecar, or lock contention as a PathError.

Path Information Cache

Each non-empty Path lazily owns one path-information cache, and ordinary copies of that path share it. Repeated Path::info() calls during the one-second cache period therefore reuse previously loaded metadata and the resolved physical path. Requesting another information part can extend the snapshot without resolving the path again while the cached resolution is current. PathInfo::reload() explicitly resolves and refreshes the path.

Directory traversal seeds each returned child path with metadata obtained by the native directory enumeration. On POSIX systems this includes the entry type when the filesystem supplies it. On Windows it also includes the size, timestamps, access approximation, and native attributes returned by FindFirstFileExW and FindNextFileW. The walker trusts each enumeration snapshot for the duration of that walk, even when processing a very large sibling set takes longer than the normal cache period.

Successful mutations through the library invalidate the cache attached to each directly affected path. External filesystem changes remain snapshot-based and become visible after cache expiry or an explicit reload.

Requesting PathInfoPart::FileIdentity loads an opaque, comparable identity for a regular filesystem object. POSIX backends derive it from device and inode information; Windows backends use volume serial and file index data. The identity is invalid when the path does not resolve to an identifiable object.

Reading Content

Path::content() opens byte and text input streams and provides bounded whole-file helpers on top of those streams. Input options default to SymlinkMode::Follow for compatibility with ordinary filesystem reads. Select Skip or Use to reject symbolic links and reparse points instead. Restrictive POSIX opens walk path components with openat and O_NOFOLLOW; Windows opens inspect every component with reparse-point processing disabled. Text reads propagate the selected policy to their underlying byte stream.

Path Diagnostics

PathError contains a PathErrorContext that describes the failed operation with a trusted title, description, and optional explicit help. It can carry source and target paths plus an immutable platform context without creating a duplicate nested error. Source-only diagnostics render path; copy, move, and rename diagnostics can render source path and target path. Path fields appear below a Paths section, while native codes and messages appear below Platform Error. Keeping the two groups explicit makes their independently aligned labels unambiguous and separates user-correctable operation values from platform-specific implementation details.

Paths and native messages cross the application trust boundary and are escaped for display. Path separators remain semantic separator nodes so terminal renderers can wrap long paths naturally. Explicit context help takes precedence over concise remedies derived from the portable platform category. A separate exception cause remains available for a genuinely independent failure layer.

Interface

class FileLock

An exclusive process lock associated with a filesystem path.

Instances are created through Path::createLock(). The operating-system lock is held on a persistent sidecar file with .lock appended to the protected path. Keeping the lock separate allows the protected file to be replaced atomically without losing mutual exclusion. Destroying or moving from this object releases the lock; the sidecar file intentionally remains to avoid races between lock users.

Public Functions

~FileLock()

Release the held lock.

FileLock(FileLock &&other) noexcept

Move a held lock from another instance.

FileLock &operator=(FileLock &&other) noexcept

Release any held lock and move another lock into this instance.

bool isLocked() const noexcept

Test whether this object currently holds a lock.

inline const Path &path() const noexcept

Get the path protected by this lock.

inline const Path &lockPath() const noexcept

Get the sidecar file on which the operating-system lock is held.

class Path

The convenience API to work with the filesystem.

Represents a relative, absolute, or partial path in the file system.

  • Paths work with the slash (‘/’) character as a path element separator on all platforms.

  • Separators are converted automatically where needed.

  • Path itself is operating system agnostic and especially handles drives (like c:/), UNC paths (like //server/share/) and POSIX roots like / on all platforms.

  • There are fromPosix() and fromWindows() methods to construct paths from a defined format if you want to make sure c:/xyz is interpreted as a relative Posix path.

Special cases - invalid paths vs. current directory:

  • Empty paths are invalid, and operations on empty paths fail as documented.

  • Paths with a single dot (.) are interpreted as the current directory and are valid.

Hard Limits:

  • Independently of the operating system, path strings with more than 8k characters or more than 1k path elements are rejected and turned into empty paths.

Windows-specific notes:

  • Windows roots are normalized: Drive letters are stored lower-case, like c:/, server names, or IP addresses in UNC paths are stored lower-case, like //server/Share.

  • Absolute paths without drive letters are not supported as they require the current working directory. They are converted into absolute POSIX paths.

  • Only on the Windows platform: Windows extended length paths are converted into its normalized form. Like “//?/C:/” becomes “c:/” and “//?/UNC/server/Share” becomes “//server/Share”.

  • Only on the Windows platform: Special Windows paths, like “/??/”, “//./”, “//?/Volume” and “//./PhysicalDrive0”, etc. are not supported. Any path that looks like a special path is converted into an empty path on construction for security reasons.

    See: Working with Paths

Public Functions

Path() = default

Creates an empty, invalid path.

explicit Path(const text::String &path) noexcept

Convert a text into a path object.

A call of this constructor always succeeds, even for malformed or invalid paths. Validate the path for the current platform using isValid() after construction.

Parameters:

path – The path to convert.

explicit Path(const std::filesystem::path &path) noexcept

Convert a path from the standard library.

Parameters:

path – The path to convert.

inline std::strong_ordering operator<=>(const Path &other) const noexcept

Compare two paths case-sensitively.

Path operator/(const Path &other) const

Join two paths (see joined)

Path operator/(const text::String &other) const

Join two paths (see joined)

Path &operator/=(const Path &other)

Join two paths (see join)

Path &operator/=(const text::String &other)

Join two paths (see join)

bool isEmpty() const noexcept

Test if this path is empty.

bool isValid() const noexcept

Test if this path is valid for the current platform.

  • Empty paths are invalid paths.

  • If the number of elements in the path is in a valid range.

  • If the path elements are valid for the current platform.

bool isRelative() const noexcept

Test if this path is relative.

bool isAbsolute() const noexcept

Test if this path is absolute.

A path is absolute if it contains a root element.

bool isRoot() const noexcept

Test if this is a root path.

Returns:

true, if the path is absolute and contains one root element.

std::strong_ordering compare(const Path &other, text::CharCompareFn compareFn = {}) const noexcept

Compare two paths.

Parameters:
  • other – The other path for comparison.

  • compareFn – The character comparison function to use.

PathFormat format() const noexcept

Get the format of this path.

unit::ItemCount elementCount() const noexcept

Get the number of path elements.

text::String element(unit::ItemIndex index) const noexcept

Access a single element of the path.

Parameters:

index – The index of the element to access.

Returns:

The element at the given index or an empty string if the index is out of range.

text::StringList elements() const noexcept

Access the individual path elements.

Path parent() const noexcept

Get the parent path.

A call of this method returns this path without the last element. An empty path is returned if this path is empty. No validation is performed.

PathList parents() const noexcept

Get all parent paths.

The returned paths are ordered from the closest to the furthest parent.

text::String root() const noexcept

Get the root element of this path.

If the path is relative, an empty string is returned. Root elements for Windows always use the slash (/) path separator, even for UNC paths. Drives always use a lower-case letter, like c:/. Server names/IP-Addresses in UNC paths are always lower-case, like //example/Share.

text::String name() const noexcept

Get the name of the last element of this path.

For a file, this is the filename, for a directory, this is the directory name.

Returns:

The name of the last element of this path, or an empty string if the path is empty.

text::String suffix() const noexcept

Get the suffix for this path.

  • If name is example.txt, .txt is returned.

  • If name is example.tar.gz, .gz is returned.

  • If name is example, an empty string is returned.

  • If name starts with a ., this is not considered a suffix.

  • If name ends with a ., this is considered a (empty) suffix (e.g. name.)

text::String suffixes() const noexcept

Get all suffixes for this path.

  • If name is example.txt, .txt is returned.

  • If name is example.tar.gz, .tar.gz is returned.

  • If name is example, an empty string is returned.

  • If name starts with a ., this is not considered a suffix.

  • If name ends with a ., this is considered a (empty) suffix (e.g. name.)

text::String stem() const noexcept

Get the name, without any suffixes.

  • If name is example, example is returned.

  • If name is example.tar.gz, example is returned.

  • If name is .hidden, .hidden is returned.

Path withName(const text::String &name) const noexcept

Return this path with the last path element replaced.

Parameters:

name – The name to use. Like example.txt.

Returns:

The new path.

Path withSuffix(const text::String &replacement) const noexcept

Return this path with all suffixes replaced.

Parameters:

replacement – The replacement to use. Like .txt. Can be empty to remove all suffixes.

Returns:

The new path.

Path withStem(const text::String &replacement) const noexcept

Return this path with the stem replaced.

Parameters:

replacement – The replacement to use. Like example.

Returns:

The new path

Path &join(const Path &other) noexcept

Join one or more path elements.

  • If other on the right is an absolute path, it is added as a relative path without its root.

  • If other is a string, it is converted into a path, then joined.

  • No validation is performed on the resulting path.

Parameters:

other – The path to join.

Path &join(const text::String &other) noexcept

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Path joined(const Path &other) const noexcept

Join one or more path elements.

  • If other on the right is an absolute path, it is added as a relative path without its root.

  • If other is a string, it is converted into a path, then joined.

  • No validation is performed on the resulting path.

Parameters:

other – The path to join.

Path joined(const text::String &other) const noexcept

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Path slice(unit::ItemRange range) const noexcept

Get a slice of this path.

Parameters:

range – The range of elements to return.

Returns:

A new path containing the specified elements, clamped to the available tail. Returns empty if the start index is out of bounds.

std::pair<Path, Path> splitAfter(unit::ItemCount count) const noexcept

Split the path after a given number of elements.

For an absolute path, if the front contains a root, the front is absolute. There are several special cases:

  • If this path is empty, both returned paths are empty too.

  • In case count is zero, front is an invalid empty path, and back contains the whole path.

  • In case count is larger than element count or infinite, front contains the whole path and back contains a . path.

Parameters:

count – The number of front elements for the split.

Returns:

The front and back part of the path.

Path resolve(PathResolveOptions options = {}) const noexcept

Resolve this path into a canonical absolute path.

Depending on the flags, it resolves any symlinks, “.” and “..” elements from the path.

Parameters:

options – The options to use.

Returns:

The resolved path or an empty path on error (or throw on error).

Path resolveOrThrow(PathResolveOptions options = {}) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Path toAbsolute(std::optional<Path> base = std::nullopt) const noexcept

Convert this path to an absolute path.

If the path is already absolute, it is returned unchanged. If the path is ., the current directory is returned. Errors: If the path is empty, or if a passed currentDirectory is empty or a relative path.

Parameters:

base – The base directory to use. If not specified, the current working directory is used.

Returns:

An absolute path or an empty path on error (or throw on error).

Path toAbsoluteOrThrow(std::optional<Path> base = std::nullopt) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Path toRelative(std::optional<Path> base = std::nullopt) const noexcept

Convert this path to a relative path.

Tries to convert an absolute path into a relative path to directory. If the path is already relative, it is returned unchanged. Errors: If the path is empty, or if a passed directory is empty, a relative path or does not have a common ancestor with this path.

Parameters:

base – The base directory to use. If not specified, the current working directory is used.

Returns:

A relative path or an empty path on error (or throw on error).

Path toRelativeOrThrow(std::optional<Path> base = std::nullopt) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

bool isRelativeTo(std::optional<Path> base = std::nullopt) const noexcept

Tests if this path is relative to the given base.

Always returns Result::Success if this path is a relative path.

Parameters:

base – The base directory to use. If not specified, the current working directory is used.

Returns:

Result::Success if this path is relative to the given base, Result::Failure otherwise.

Path commonAncestor(std::optional<Path> base = std::nullopt) const noexcept

Get the common ancestor with the given path.

Parameters:

base – The base directory to use. If not specified, the current working directory is used.

Returns:

The common ancestor path or an empty path if no common ancestor exists.

FileLock createLock() const

Acquire a nonblocking exclusive process lock associated with this path.

The lock is held on a persistent .lock sidecar so this path can safely be replaced while locked.

Throws:

PathError – If this path is invalid, the sidecar cannot be opened, or another process holds the lock.

Returns:

The RAII object holding the lock.

PathInfo info(PathInfoParts parts = PathInfoPart::Default) const noexcept

Access information about the file or directory of this path.

Repeated calls on this path or one of its copies share the attached information cache.

Parameters:

parts – The parts to initially request and cache.

PathWalker walker() const noexcept

Access the path walker component for this path.

PathContent content() const

Access the content of the path.

PathOperations operations() const noexcept

Access the path operations.

std::filesystem::path toStdPath() const noexcept

Convert this path to a standard library path.

text::String toPosix() const noexcept

Convert this path to a POSIX path.

Returns an empty string if the path is an absolute Windows path.

Returns:

A string with the path, using slash (/) path separators.

text::String toWindows(PathWindowsFormat format = PathWindowsFormat::Extended) const noexcept

Convert this path to a Windows native path.

Returns an empty string if the path is an absolute Posix path.

Parameters:

format – The output format for the Windows path.

Returns:

The window native path.

text::String toString() const noexcept

Creates a string for display, joining the path using (/) path separators.

Returns:

A platform-agnostic string for display.

Public Static Functions

static Path fromElements(const text::StringList &elements) noexcept

Assemble a path for several path elements.

Parameters:

elements – The path elements to join into a path.

Returns:

The assembled path.

static Path fromPosix(const text::String &path) noexcept

Convert a POSIX path.

A call of this method ignores any Window-specific handling.

Parameters:

path – The string with the path to convert.

Returns:

The converted path or an empty path if the path is not a valid POSIX path.

static Path fromPosixOrThrow(const text::String &path)

Convert a POSIX path.

A call of this method ignores any Window-specific handling.

Parameters:

path – The string with the path to convert.

Throws:

err::ParseError – If the path is not a valid POSIX path.

Returns:

The converted path.

static Path fromWindows(const text::String &path) noexcept

Convert a Windows path.

A call of this method ignores any Posix-specific handling.

Parameters:

path – The string with the path to convert.

Returns:

The converted path or an empty path if the path is not a valid Windows path.

static Path fromWindowsOrThrow(const text::String &path)

Convert a Windows path.

A call of this method ignores any Posix-specific handling.

Parameters:

path – The string with the path to convert.

Throws:

err::ParseError – If the path is not a valid Windows path.

Returns:

The converted path.

static Path fromNative(const text::String &path) noexcept

Convert a POSIX or Windows path, depending on the current platform.

This is the same as calling fromPosix() or fromWindows().

Parameters:

path – The string with the path to convert.

Returns:

The converted path or an empty path if the path is not valid for the platform.

static Path fromNativeOrThrow(const text::String &path)

Convert a POSIX or Windows path, depending on the current platform.

This is the same as calling fromPosix() or fromWindows().

Parameters:

path – The string with the path to convert.

Throws:

err::ParseError – If the path is not valid for the current platform.

Returns:

The converted path.

static const Path &empty() noexcept

Return the shared empty, invalid path.

Returns:

An empty path.

static Path currentDirectory() noexcept

Return a path to the current working directory of the process.

Returns:

An absolute path to the current working directory.

static Path executablePath() noexcept

Return the absolute executable image path of the current process.

Returns:

The executable image path, or an empty path on error.

static Path executablePathOrThrow()

Return the absolute executable image path of the current process.

Throws:

PathError – If the executable path cannot be determined or converted.

Returns:

The executable image path.

static Path userHomeDirectory() noexcept

Return the home directory for the effective user of this process.

This lookup uses the operating-system account database and does not inspect environment variables.

Returns:

An absolute path to the effective user’s home directory, or an empty path on error.

static Path userHomeDirectoryOrThrow()

Return the home directory for the effective user of this process.

This lookup uses the operating-system account database and does not inspect environment variables.

Throws:

PathError – if the home directory cannot be determined or converted.

Returns:

An absolute path to the effective user’s home directory.

static Path systemTempDirectory() noexcept

Return the system directory for temporary files and directories.

Returns:

An absolute path to the system temporary directory, or an empty path on error.

static Path systemTempDirectoryOrThrow()

Return the system directory for temporary files and directories.

Throws:

PathError – if the temporary directory cannot be determined or converted.

Returns:

An absolute path to the system temporary directory.

static Path currentElement() noexcept

Return a “current” path (“.”).

Returns:

The special valid current path.

static Path parentElement() noexcept

Return a “parent” path (“..”).

Returns:

The special valid parent path.

class PathAccessInfo

Best-effort portable access information for a path.

Public Functions

PathAccessInfo() = default

Create empty access information.

inline PathAccessRights currentProcessRights() const noexcept

Access rights for the current process.

inline PathAccessInfo &setCurrentProcessRights(const PathAccessRights value) noexcept

Set access rights for the current process.

inline bool hasPortableRights() const noexcept

Test if owner/group/other rights are available.

inline PathAccessInfo &setHasPortableRights(const bool value) noexcept

Set whether owner/group/other rights are available.

inline PathAccessRights ownerRights() const noexcept

Access rights for the owner class.

inline PathAccessInfo &setOwnerRights(const PathAccessRights value) noexcept

Set access rights for the owner class.

inline PathAccessRights groupRights() const noexcept

Access rights for the group class.

inline PathAccessInfo &setGroupRights(const PathAccessRights value) noexcept

Set access rights for the group class.

inline PathAccessRights otherRights() const noexcept

Access rights for all other users.

inline PathAccessInfo &setOtherRights(const PathAccessRights value) noexcept

Set access rights for all other users.

enum class erbsland::path::PathAccessProfile : uint8_t

Portable access profile for creating or changing files and directories.

Values:

enumerator Default

Use platform defaults.

enumerator UserOnly

Only the current user should have regular access.

enumerator UserAndGroup

The current user and group should have regular access.

enumerator Everyone

Everyone should have regular access.

enum class erbsland::path::PathAccessRight : uint8_t

Portable access rights for files and directories.

Values:

enumerator None

No access rights.

enumerator Read

The object can be read.

enumerator Write

The object can be modified.

enumerator Execute

File execution or directory traversal/search.

enumerator All

All portable rights.

using erbsland::path::PathAccessRights = util::EnumFlags<PathAccessRight>

A set of portable access rights.

enum class erbsland::path::PathAttribute : uint8_t

Common native file attributes that are not covered by portable access rights.

Values:

enumerator None

No attributes.

enumerator ReadOnly

Windows read-only attribute.

enumerator Immutable

POSIX/macOS immutable flag, where supported.

enumerator Hidden

Native hidden attribute, where supported.

enumerator Archive

Windows archive attribute.

enumerator System

Windows system attribute.

enumerator All

All known native attributes.

using erbsland::path::PathAttributes = util::EnumFlags<PathAttribute>

A set of native file attributes.

class PathChangeOptions

Options for changing path metadata.

Public Functions

PathChangeOptions() = default

Create path-change options with their default values.

inline bool recursive() const noexcept

Apply the change recursively.

inline PathChangeOptions &setRecursive(const bool value) noexcept

Set whether to apply the change recursively.

inline bool ignoreErrors() const noexcept

Ignore errors while applying changes.

inline PathChangeOptions &setIgnoreErrors(const bool value) noexcept

Set whether to ignore errors while applying changes.

inline SymlinkMode symlinkMode() const noexcept

How to handle symbolic links.

inline PathChangeOptions &setSymlinkMode(const SymlinkMode value) noexcept

Set how to handle symbolic links.

enum class erbsland::path::PathCollisionMode : uint8_t

The mode to use when a path collision is detected for an operation.

Values:

enumerator Stop

Stop processing the path (with an error)

enumerator Skip

Skip the path.

enumerator Overwrite

Overwrite the existing path.

class PathContent

Allows access to the content of a path.

Public Functions

PathContent()

Create an empty instance.

explicit PathContent(const Path &path)

Create a new instance for the given path.

~PathContent()

Release the state used for path-content operations.

PathContent &operator=(PathContent&&) noexcept

Move path-content state into this instance.

bool isEmpty() const

Test if the path is empty.

const Path &path() const

Access the underlying path.

std::optional<text::String> readText(PathReadTextOptions options = {}) const noexcept

Read the contents of a file into a string.

In strict encoding mode, this function returns no string instead of propagating an encoding exception.

Parameters:

options – The read options.

Returns:

The string read from the file or std::nullopt on any error.

text::String readTextOrThrow(PathReadTextOptions options = {}) const

Read the contents of a file into a string.

Parameters:

options – The read options.

Throws:
  • PathError – if the operation failed (no file, access errors, etc.)

  • text::EncodingError – if the operation failed due to encoding errors.

  • err::OutOfRangeError – if the file exceeds a set maximum length.

Returns:

The string read from the file.

std::optional<mem::ByteBlock> readData(PathReadDataOptions options = {}) const noexcept

Read the contents of a file as byte data.

Parameters:

options – The read options.

Returns:

The byte block read from the file or std::nullopt on any error.

mem::ByteBlock readDataOrThrow(PathReadDataOptions options = {}) const

Read the contents of a file as byte data.

Parameters:

options – The read options.

Throws:
  • PathError – if the operation failed (no file, access errors, etc.)

  • err::OutOfRangeError – if the file exceeds a set maximum length.

Returns:

The byte block read from the file.

util::Result writeText(const text::String &text, PathWriteTextOptions options = {}) const noexcept

Write text into the file at this path.

Parameters:
  • text – The text to write.

  • options – The options to use.

Returns:

True on success, false on error.

void writeTextOrThrow(const text::String &text, PathWriteTextOptions options = {}) const

Write text into the file at this path.

Parameters:
  • text – The text to write.

  • options – The options to use.

Throws:

PathError – if the operation failed (no file, access errors, etc.)

util::Result writeData(const mem::ByteBlock &data, PathWriteDataOptions options = {}) const noexcept

Write byte data into a file at this path.

Parameters:
  • options – The options to use.

  • data – The data to write.

Returns:

True on success, false on error.

void writeDataOrThrow(const mem::ByteBlock &data, PathWriteDataOptions options = {}) const

Write byte data into a file at this path.

Parameters:
  • options – The options to use.

  • data – The data to write.

Throws:

PathError – if the operation failed (no file, access errors, etc.)

stream::TextInputStreamPtr openTextInputStream(PathReadTextOptions options = {}) const

Open a file as a text stream for reading.

The read limits (bytes and code-points) are ignored when reading from a stream.

Parameters:

options – The options to use.

Throws:

PathError – if the operation failed (no file, access errors, etc.)

Returns:

The open stream.

stream::TextOutputStreamPtr openTextOutputStream(PathWriteTextOptions options = {}) const

Open a file as a text stream for writing.

Parameters:

options – The options to use.

Throws:

PathError – if the operation failed (no file, access errors, etc.)

Returns:

The open stream.

stream::ByteInputStreamPtr openByteInputStream(PathReadDataOptions options = {}) const

Open a file as byte data for reading.

Parameters:

options – The options to use.

Throws:

PathError – if the operation failed (no file, access errors, etc.)

Returns:

The open stream.

stream::ByteOutputStreamPtr openByteOutputStream(PathWriteDataOptions options = {}) const

Open a file as byte data for writing.

Parameters:

options – The options to use.

Throws:

PathError – if the operation failed (no file, access errors, etc.)

Returns:

The open stream.

class PathCopyOptions

The options for a copy operation.

Public Functions

PathCopyOptions() = default

Create path-copy options with their default values.

inline bool ignoreErrors() const noexcept

Whether filesystem errors are ignored while copying remaining entries.

inline PathCopyOptions &setIgnoreErrors(const bool value) noexcept

Set whether filesystem errors are ignored while copying remaining entries.

inline bool recursive() const noexcept

Whether directory contents are copied recursively.

inline PathCopyOptions &setRecursive(const bool value) noexcept

Set whether directory contents are copied recursively.

inline PathCollisionMode collisionMode() const noexcept

The behavior when the exact destination path already exists.

inline PathCopyOptions &setCollisionMode(const PathCollisionMode value) noexcept

Set the behavior when the exact destination path already exists.

inline SymlinkMode symlinkMode() const noexcept

The behavior for symbolic links encountered by the copy operation.

inline PathCopyOptions &setSymlinkMode(const SymlinkMode value) noexcept

Set the behavior for symbolic links encountered by the copy operation.

inline bool createParents() const noexcept

Whether missing destination parent directories are created.

inline PathCopyOptions &setCreateParents(const bool value) noexcept

Set whether missing destination parent directories are created.

inline bool prescan() const noexcept

Whether the source is scanned first to calculate an exact progress total.

inline PathCopyOptions &setPrescan(const bool value) noexcept

Set whether the source is scanned first to calculate an exact progress total.

class PathCreateDirectoryOptions

Options for creating directories.

Public Functions

PathCreateDirectoryOptions() = default

Create directory-creation options with their default values.

inline bool createParents() const noexcept

Create the parent directories if they do not exist.

inline PathCreateDirectoryOptions &setCreateParents(const bool value) noexcept

Set whether to create the parent directories if they do not exist.

inline PathCreateMode creationMode() const noexcept

The creation mode for the directory.

inline PathCreateDirectoryOptions &setCreationMode(const PathCreateMode mode) noexcept

Set the creation mode for the directory.

inline PathAccessProfile accessProfile() const noexcept

The access profile for newly created directories.

inline PathCreateDirectoryOptions &setAccessProfile(const PathAccessProfile value) noexcept

Set the access profile for newly created directories.

class PathCreateFileOptions

Options for creating/opening files for writing.

Public Functions

PathCreateFileOptions() = default

Create file-creation options with their default values.

inline bool createParents() const noexcept

Create the parent directories if they do not exist.

inline PathCreateFileOptions &setCreateParents(const bool value) noexcept

Set whether to create the parent directories if they do not exist.

inline PathCreateMode creationMode() const noexcept

The creation mode for the file.

inline PathCreateFileOptions &setCreationMode(const PathCreateMode mode) noexcept

Set the creation mode for the file.

inline PathAccessProfile accessProfile() const noexcept

The access profile for newly created files.

inline PathCreateFileOptions &setAccessProfile(const PathAccessProfile value) noexcept

Set the access profile for newly created files.

enum class erbsland::path::PathCreateMode : std::uint8_t

The mode to use when creating a file or directory.

Values:

enumerator CreateOrOverwrite

Create or overwrite.

  • For file streams: Create a new file or overwrite an existing file.

  • For directories: Create a new directory or keep an existing one.

  • For empty files: Create an empty file, overwriting an existing file with an empty one.

enumerator CreateOrAppend

Create or append.

  • For file streams: Create a new file or append to an existing file.

  • For directories: Create a new directory or keep an existing one.

  • For empty files: Create an empty file, or update modification time of an existing file, without changing the file content.

enumerator CreateNew

Only create new.

  • For file streams: Only create a new file. Fail if the file already exists.

  • For directories: Only create a new directory. Fail if the directory already exists.

  • For empty files: Only create a new empty file. Fail if the file already exists.

class PathError : public erbsland::err::RuntimeError

An error related to filesystem paths.

Public Functions

explicit PathError(text::String title, std::exception_ptr cause = {}) noexcept

Create a path error with a title only.

explicit PathError(PathErrorContext context, std::exception_ptr cause = {}) noexcept

Create a path error with detailed context.

virtual err::DiagnosticConstPtr diagnostic() const override

Convert the error with all its details into a structured diagnostic.

inline const text::String &title() const noexcept

Get the operation title.

inline const text::String &description() const noexcept

Get the operation description.

inline text::String help() const noexcept

Get explicit or category-derived help.

inline const text::String &sourcePath() const noexcept

Get the source path, or an empty view.

inline const text::String &targetPath() const noexcept

Get the target path, or an empty view.

inline const system::PlatformErrorContextConstPtr &platformContext() const noexcept

Get the immutable native failure context, if available.

inline const PathErrorContext &context() const noexcept

Get the complete path error context.

class PathErrorContext

User-facing context for a path-domain error.

Public Functions

explicit PathErrorContext(text::String title, text::String description = {}) noexcept

Create a context for a failed path operation.

Parameters:
  • title – A short developer-authored title.

  • description – An optional developer-authored explanation.

inline const text::String &title() const noexcept

Get the operation title.

PathErrorContext &setTitle(text::String title) noexcept

Set the operation title.

inline const text::String &description() const noexcept

Get the operation description.

PathErrorContext &setDescription(text::String description) noexcept

Set the operation description.

text::String help() const noexcept

Get explicit help or category-derived help when available.

PathErrorContext &setHelp(text::String help) noexcept

Set explicit help, overriding category-derived help.

inline const text::String &sourcePath() const noexcept

Get the source path, or an empty view if none was provided.

PathErrorContext &setSourcePath(text::String sourcePath) noexcept

Set the source path.

inline const text::String &targetPath() const noexcept

Get the target path, or an empty view if none was provided.

PathErrorContext &setTargetPath(text::String targetPath) noexcept

Set the target path.

inline const system::PlatformErrorContextConstPtr &platformContext() const noexcept

Get the immutable native failure context, if available.

PathErrorContext &setPlatformContext(system::PlatformErrorContextConstPtr platformContext) noexcept

Set the immutable native failure context.

enum class erbsland::path::PathFormat : uint8_t

The format of a path.

Values:

enumerator Generic

A generic path that works on all platforms.

enumerator Posix

A POSIX path that works on macOS and Linux (like /...).

enumerator Windows

A Windows path that works on Windows (like C:/... or //server/share/...).

class PathInfo

Information about a file or directory.

Caching:

  • The cache is attached to the original Path value and shared by its copies. Repeated Path::info() calls for that value therefore reuse the same snapshot.

  • Directory walks preload every metadata field returned by the native directory scan. A walk trusts these scan snapshots for the duration of the walk.

  • A call of reload() invalidates cached information immediately and triggers path resolving.

  • Without manually calling reload(), the cache is automatically invalidated after one second.

  • Successful library mutations invalidate the cache attached to the directly affected path.

    See: File-System Paths

    Empty/Unresolved/Non-Existing Behavior:

  • exists() returns false.

  • resolvedPath() returns an empty path.

  • type() returns PathType::Unknown and therefore all related is...() functions return false.

  • fileSize() returns 0.

  • All time functions return DateTime::isValid() == false.

  • All owner/group functions either throw an error or return an empty typed value. Changing State between Calls:

  • If at a point an existing path vanishes or gets inaccessible (causing an error while looking up new information), the path info invalidates the cached information and behaves like an unresolved path.

  • Only reload() can bring a path info instance back to a valid state. Symlinks:

  • The path information never follows symbolic links.

  • It uses PathResolveMode::PhysicalNoFinalSymlink to resolve the path.

  • If you need to follow symbolic links, resolve the path yourself before accessing the path info.

Public Functions

PathInfo() = default

Creates an empty path info instance.

explicit PathInfo(const Path &path, PathInfoParts parts = PathInfoPart::Default) noexcept

Create a new path info instance for the given path.

The given path is resolved to a canonical absolute path if this is not already the case. If resolving fails, the path info behaves like empty path info. Yet path() returns the original path passed to the constructor, and therefore calling reload() may resolve the path again.

Parameters:
  • path – The path to get information about.

  • parts – The parts to initially request and cache.

PathInfo &operator=(PathInfo &&other) noexcept

Move cached path information from another instance.

bool isEmpty() const noexcept

Test if the path behind this info is empty.

const Path &path() const noexcept

Access the original path passed to the constructor.

const Path &resolvedPath() const noexcept

Test if the path info is in a valid state.

The path info is valid if the path exists and could be resolved, and the cached information is valid. Access the resolved physical absolute path. Empty if the path does not exist and resolving failed.

bool exists() const noexcept

Test if this path exists.

inline bool isDirectory() const noexcept

Test if this path is a directory.

inline bool isRegularFile() const noexcept

Test if this is a regular file.

inline bool isSymlink() const noexcept

Test if this is a symlink.

inline bool isDevice() const noexcept

Test if this is a device.

inline bool isSocket() const noexcept

Test if this is a socket.

inline bool isPipe() const noexcept

Test if this is a pipe.

inline bool isReparsePoint() const noexcept

Test if this is a reparse point.

bool isReadable() const noexcept

Test if the current process can read this path.

bool isWritable() const noexcept

Test if the current process can write this path.

bool isExecutable() const noexcept

Test if the current process can execute or traverse this path.

PathType type() const noexcept

Get the type of the resource behind this path.

unit::ByteLength fileSize() const noexcept

The size of the file in bytes.

Returns:

The size of the file in bytes, or zero if the file does not exist or the path is no file.

system::FileIdentity fileIdentity() const noexcept

Get the stable identity of the current filesystem object.

Returns:

An invalid identity if the path does not exist or identity lookup failed.

time::DateTime lastModified() const noexcept

Get the last modified time.

It is available on all platforms. The returned time is always in the UTC time zone.

Returns:

The date/time, or an invalid date/time if the file/directory does not exist or the attributes cannot be obtained.

time::DateTime lastAccessed() const noexcept

Get the last accessed time.

It is available on all platforms. The returned time is always in the UTC time zone.

Returns:

The date/time, or an invalid date/time if the file/directory does not exist or the attributes cannot be obtained.

time::DateTime birthTime() const noexcept

Get the creation time, when the file/directory originally was created.

It is not available on all Linux filesystems/kernel-versions. The returned time is always in the UTC time zone.

Returns:

The date/time, or an invalid date/time if the file/directory does not exist or the attributes cannot be obtained.

time::DateTime lastMetadataChange() const noexcept

Get the time of the last metadata change.

This is not available on Windows. The returned time is always in the UTC time zone.

Returns:

The date/time, or an invalid date/time if the file/directory does not exist or the attributes cannot be obtained.

time::DateTime creationTime() const noexcept

Get the best effort “create” time.

This function tries to get the creation time of the file/directory. If this time isn’t available for this platform, it tries the next best equivalent: falling back to the last metadata change, falling back to the last modified time.

Returns:

The date/time, or an invalid date/time if the file/directory does not exist or the attributes cannot be obtained.

system::UserName ownerName() const noexcept

Get the name of the owner of the file/directory.

Posix: This is the username. Windows: This is the resolved username with a separate domain.

Returns:

The name of the owner or an empty name if it does not exist or cannot be obtained.

system::UserName ownerNameOrThrow() const

Get the name of the owner of the file/directory.

Throws:

PathError – If the owner cannot be obtained.

Returns:

The name of the owner

system::UserId ownerId() const noexcept

Get the identifier of the owner of the file/directory.

Posix: This is the UID. Windows: This is the SID.

Returns:

The identifier of the owner or an empty identifier if it does not exist or cannot be obtained.

system::UserId ownerIdOrThrow() const

Get the identifier of the owner of the file/directory.

Throws:

PathError – If the owner cannot be obtained.

Returns:

The identifier of the owner.

system::GroupName groupName() const noexcept

Get the owning group for the file/directory.

Posix: This is the groupname. Windows: This is the resolved groupname with a separate domain.

Returns:

The name of the group or an empty name if it does not exist or cannot be obtained.

system::GroupName groupNameOrThrow() const

Get the owning group for the file/directory.

Throws:

PathError – If the group cannot be obtained.

Returns:

The name of the group.

system::GroupId groupId() const noexcept

Get the identifier of the owning group of the file/directory.

Posix: This is the GID. Windows: This is the SID.

Returns:

The identifier of the group or an empty identifier if it does not exist or cannot be obtained.

system::GroupId groupIdOrThrow() const

Get the identifier of the owning group of the file/directory.

Throws:

PathError – If the group cannot be obtained.

Returns:

The identifier of the group.

PathAccessInfo accessInfo() const noexcept

Get portable access information.

PathAccessInfo accessInfoOrThrow() const

Get portable access information.

Throws:

PathError – If access information cannot be obtained.

PathAttributes attributes() const noexcept

Get native path attributes.

PathAttributes attributesOrThrow() const

Get native path attributes.

Throws:

PathError – If native attributes cannot be obtained.

bool hasAttribute(PathAttribute attribute) const noexcept

Test if this path has the given native attribute.

void reload()

Reload the information about the file or directory of this path.

This will use the original path, retry canonicalization, and refresh the information.

void reload(PathInfoParts parts)

Reload and preload the given information parts.

This will use the original path, retry canonicalization, and refresh the information.

enum class erbsland::path::PathInfoPart : uint16_t

The part of path information to request and cache.

Values:

enumerator None

No parts requested.

enumerator Type

The type of the path and if it exists. Also resolving the path.

enumerator Size

The size of the path when it is a regular file.

enumerator Times

All time information.

enumerator OwnerId

The owner identifier.

enumerator OwnerName

The resolved owner name.

enumerator GroupId

The group identifier.

enumerator GroupName

The resolved group name.

enumerator AccessRights

Portable access rights.

enumerator Attributes

Native attributes.

enumerator FileIdentity

Stable identity of the current filesystem object.

enumerator Owner

The owner identifier and name.

enumerator Group

The group identifier and name.

enumerator Identity

Owner and group identifiers and names.

enumerator Default

The default parts to request.

enumerator All

All parts requested.

using erbsland::path::PathInfoParts = util::EnumFlags<PathInfoPart>

The parts of path information to initially request and cache.

class PathMoveOptions

The options for moving a path.

Public Functions

PathMoveOptions() = default

Create path-move options with their default values.

inline bool ignoreErrors() const noexcept

Ignore all errors.

inline PathMoveOptions &setIgnoreErrors(const bool value) noexcept

Set whether to ignore all errors.

inline PathCollisionMode collisionMode() const noexcept

Behavior on collision.

inline PathMoveOptions &setCollisionMode(const PathCollisionMode value) noexcept

Set the behavior on collision.

inline bool createParents() const noexcept

Create parent directories if they do not exist.

inline PathMoveOptions &setCreateParents(const bool value) noexcept

Set whether to create parent directories if they do not exist.

class PathOperations

A class for performing operations on paths.

Public Functions

PathOperations()

Create an empty/invalid path operations instance.

explicit PathOperations(const Path &path)

Create a path operations instance for the given path.

~PathOperations()

dtor

PathOperations &operator=(PathOperations&&) noexcept

Move another path-operations instance into this instance.

bool isEmpty() const

Test if the path is empty.

const Path &path() const

Access the underlying path.

util::Result remove(PathRemoveOptions options = {}, const PathProgressFn &progressFn = {}) noexcept

Remove a file or directory.

Parameters:
  • options – Options for the remove operation.

  • progressFn – Optional progress callback.

Returns:

Result::Success if the operation was successful, Result::Failure otherwise.

void removeOrThrow(PathRemoveOptions options = {}, const PathProgressFn &progressFn = {})

Remove a file or directory.

Parameters:
  • options – Options for the remove operation.

  • progressFn – Optional progress callback.

Throws:

PathError – if the operation failed, unless IgnoreErrors is set.

auto copyTo(const Path &destination, PathCopyOptions options = {}, const PathProgressFn &progressFn = {}) const noexcept -> util::Result

Copy a file or directory.

Parameters:
  • destination – The destination path.

  • options – Options for the copy operation.

  • progressFn – Optional progress callback.

Returns:

Result::Success if the operation was successful, Result::Failure otherwise.

void copyToOrThrow(const Path &destination, PathCopyOptions options = {}, const PathProgressFn &progressFn = {}) const

Copy a file or directory.

Parameters:
  • destination – The destination path.

  • options – Options for the copy operation.

  • progressFn – Optional progress callback.

Throws:

PathError – if the operation failed, unless IgnoreErrors is set.

util::Result moveTo(const Path &destination, PathMoveOptions options = {}) const noexcept

Moves/renames a path.

Parameters:
  • destination – The destination path. Must be on the same filesystem.

  • options – Options for the move operation.

Returns:

Result::Success if the operation was successful, Result::Failure otherwise.

void moveToOrThrow(const Path &destination, PathMoveOptions options = {}) const

Moves/renames a path.

Parameters:
  • destination – The destination path. Must be on the same filesystem.

  • options – Options for the move operation.

Throws:

PathError – if the operation failed, unless IgnoreErrors is set.

util::Result createFile(PathCreateFileOptions options = {}) const noexcept

Create an empty file.

Parameters:

options – Options for the operation.

Returns:

Result::Success if the operation was successful, Result::Failure otherwise.

void createFileOrThrow(PathCreateFileOptions options = {}) const

Create an empty file.

Parameters:

options – Options for the operation.

Throws:

PathError – if the operation failed, unless IgnoreErrors is set.

util::Result createDirectory(PathCreateDirectoryOptions options = {}) const noexcept

Create a directory.

Parameters:

options – Options for the operation.

Returns:

Result::Success if the operation was successful, Result::Failure otherwise.

void createDirectoryOrThrow(PathCreateDirectoryOptions options = {}) const

Create a directory.

Parameters:

options – Options for the operation.

Throws:

PathError – if the operation failed, unless IgnoreErrors is set.

TempDirectoryPtr createTempDirectory(PathTempDirectoryOptions options = {}) const noexcept

Create a temporary directory under this path.

Parameters:

options – Options for the operation.

Returns:

A shared temporary directory handle, or nullptr on error.

TempDirectoryPtr createTempDirectoryOrThrow(PathTempDirectoryOptions options = {}) const

Create a temporary directory under this path.

Parameters:

options – Options for the operation.

Throws:

PathError – if the operation failed.

Returns:

A shared temporary directory handle.

stream::TempByteOutputStreamPtr openTempByteOutputStream(PathTempFileOptions options = {}) const noexcept

Create and open a temporary byte output stream under this path.

Parameters:

options – Options for the operation.

Returns:

A temporary byte output stream, or nullptr on error.

stream::TempByteOutputStreamPtr openTempByteOutputStreamOrThrow(PathTempFileOptions options = {}) const

Create and open a temporary byte output stream under this path.

Parameters:

options – Options for the operation.

Throws:

PathError – if the operation failed.

Returns:

A temporary byte output stream.

auto openTempTextOutputStream(PathTempFileOptions temporaryOptions = {}, PathWriteTextOptions writeOptions = {}) const noexcept -> stream::TempTextOutputStreamPtr

Create and open a temporary text output stream under this path.

Parameters:
  • temporaryOptions – Options for creating the temporary file.

  • writeOptions – Options for writing encoded text.

Returns:

A temporary text output stream, or nullptr on error.

auto openTempTextOutputStreamOrThrow(PathTempFileOptions temporaryOptions = {}, PathWriteTextOptions writeOptions = {}) const -> stream::TempTextOutputStreamPtr

Create and open a temporary text output stream under this path.

Parameters:
  • temporaryOptions – Options for creating the temporary file.

  • writeOptions – Options for writing encoded text.

Throws:

PathError – if the operation failed.

Returns:

A temporary text output stream.

util::Result setAccessProfile(PathAccessProfile profile, PathChangeOptions options = {}) const noexcept

Set a portable access profile for this path.

Parameters:
  • profile – The access profile to apply.

  • options – Options for the operation.

Returns:

Result::Success if the operation was successful, Result::Failure otherwise.

void setAccessProfileOrThrow(PathAccessProfile profile, PathChangeOptions options = {}) const

Set a portable access profile for this path.

Parameters:
  • profile – The access profile to apply.

  • options – Options for the operation.

Throws:

PathError – if the operation failed.

util::Result addAttributes(PathAttributes attributes, PathChangeOptions options = {}) const noexcept

Add native path attributes.

Parameters:
  • attributes – The attributes to add.

  • options – Options for the operation.

Returns:

Result::Success if the operation was successful, Result::Failure otherwise.

void addAttributesOrThrow(PathAttributes attributes, PathChangeOptions options = {}) const

Add native path attributes.

Parameters:
  • attributes – The attributes to add.

  • options – Options for the operation.

Throws:

PathError – if the operation failed.

util::Result clearAttributes(PathAttributes attributes, PathChangeOptions options = {}) const noexcept

Clear native path attributes.

Parameters:
  • attributes – The attributes to clear.

  • options – Options for the operation.

Returns:

Result::Success if the operation was successful, Result::Failure otherwise.

void clearAttributesOrThrow(PathAttributes attributes, PathChangeOptions options = {}) const

Clear native path attributes.

Parameters:
  • attributes – The attributes to clear.

  • options – Options for the operation.

Throws:

PathError – if the operation failed.

struct PathProgress

The progress after the current operation.

Public Members

PathProgressStatus status

The status after the current operation.

unit::ItemCount total

Total paths to process, or infinite if unknown.

unit::ItemCount processed

Number of paths processed so far.

unit::ItemCount errors

Number of errors encountered while ignoring errors.

enum class erbsland::path::PathProgressStatus : uint8_t

The status after the current operation.

Values:

enumerator Success
enumerator Failed
class PathReadDataOptions

The options for reading data from a file.

Public Functions

PathReadDataOptions() noexcept = default

Create path-read options with their default values.

inline unit::ByteLength maximumByteLength() const noexcept

Get the maximum number of bytes to read.

inline PathReadDataOptions &setMaximumByteLength(const unit::ByteLength value) noexcept

Set the maximum number of bytes to read.

inline SymlinkMode symlinkMode() const noexcept

Get how symbolic links are handled while opening the input file.

inline PathReadDataOptions &setSymlinkMode(const SymlinkMode value) noexcept

Set how symbolic links are handled while opening the input file.

Use has the same restrictive behavior as Skip, because a symbolic link has no regular file content.

inline time::TimeDelta timeout() const noexcept

Get the maximum wait for one stream operation.

inline PathReadDataOptions &setTimeout(const time::TimeDelta value) noexcept

Set the maximum wait for one stream operation.

inline const stream::InputStreamSettings &streamSettings() const noexcept

Get the stream settings.

inline PathReadDataOptions &setStreamSettings(const stream::InputStreamSettings &value) noexcept

Set the stream settings.

Public Static Attributes

static const auto cDefaultTimeout = time::TimeDelta::seconds(60)

The default timeout for whole-file path operations.

static const auto cDefaultMaximumByteLength = unit::ByteLength{10'000'000LL}

The default maximum byte length for whole-file read operations.

class PathReadTextOptions

The options for reading text from a file.

Public Functions

PathReadTextOptions() = default

Create the default options.

PathReadTextOptions(unit::ByteLength maximumByteLength)

Create UTF-8, replacement char and automatic BOM with a maximum byte length.

Parameters:

maximumByteLength – The maximum byte length to read.

PathReadTextOptions(unit::CpLength maximumCpLength)

Create UTF-8, replacement char and automatic BOM with a maximum code-point length.

Parameters:

maximumCpLength – The maximum code-point length to read.

PathReadTextOptions(text::StringEncoding encoding)

Use defaults with a different encoding.

Parameters:

encoding – The encoding to use.

inline text::StringEncoding encoding() const

Get the text encoding.

PathReadTextOptions &setEncoding(text::StringEncoding value)

Set the text encoding.

inline text::StringBomMode bomMode() const

Get the byte-order-mark mode.

PathReadTextOptions &setBomMode(text::StringBomMode value)

Set the byte-order-mark mode.

inline text::EncodingMode encodingMode() const

Get the handling mode for encoding errors.

PathReadTextOptions &setEncodingMode(text::EncodingMode value)

Set the handling mode for encoding errors.

inline unit::ByteLength maximumByteLength() const

Get the maximum number of bytes to read.

PathReadTextOptions &setMaximumByteLength(unit::ByteLength value)

Set the maximum number of bytes to read.

inline unit::CpLength maximumCpLength() const

Get the maximum number of code points to read.

PathReadTextOptions &setMaximumCpLength(unit::CpLength value)

Set the maximum number of code points to read.

inline SymlinkMode symlinkMode() const noexcept

Get how symbolic links are handled while opening the input file.

inline PathReadTextOptions &setSymlinkMode(const SymlinkMode value) noexcept

Set how symbolic links are handled while opening the input file.

Use has the same restrictive behavior as Skip, because a symbolic link has no regular file content.

inline time::TimeDelta timeout() const noexcept

Get the maximum wait for one stream operation.

PathReadTextOptions &setTimeout(time::TimeDelta value) noexcept

Set the maximum wait for one stream operation.

inline stream::StreamBuffering buffering() const noexcept

Get the intended balance between memory use and throughput.

PathReadTextOptions &setBuffering(stream::StreamBuffering value) noexcept

Set the intended balance between memory use and throughput.

inline bool isSensitive() const noexcept

Test if library-owned input buffers use secure erasure.

PathReadTextOptions &setSensitive(bool value) noexcept

Enable or disable secure erasure for library-owned input buffers.

inline const stream::InputStreamSettings &streamSettings() const noexcept

Get the stream settings.

PathReadTextOptions &setStreamSettings(const stream::InputStreamSettings &value) noexcept

Set the stream settings.

Public Static Attributes

static const auto cDefaultTimeout = time::TimeDelta::seconds(60)

The default timeout for whole-file path operations.

class PathRemoveOptions

Options for removing a file or directory tree.

Public Functions

PathRemoveOptions() = default

Create path-removal options with their default values.

inline bool recursive() const noexcept

Remove all directories and files recursively.

inline PathRemoveOptions &setRecursive(const bool value) noexcept

Set whether to remove all directories and files recursively.

inline bool ignoreErrors() const noexcept

Ignore all errors when removing the path.

This will leave files and directories that cause errors in place.

inline PathRemoveOptions &setIgnoreErrors(const bool value) noexcept

Set whether to ignore all errors when removing the path.

inline bool keepBase() const noexcept

Keep any base directory in place.

inline PathRemoveOptions &setKeepBase(const bool value) noexcept

Set whether to keep any base directory in place.

inline bool prescan() const noexcept

Prescan the directory for recursive removal to get a better progress estimate (slower).

inline PathRemoveOptions &setPrescan(const bool value) noexcept

Set whether to prescan the directory for recursive removal to get a better progress estimate (slower).

enum class erbsland::path::PathResolveMode : uint8_t

The mode how to resolve a path.

Values:

enumerator Lexical

Only normalize the path without touching the file system.

  • Removing redundant path elements, such as ., .., //.

enumerator Weak

Resolve the path to its physical location as far as possible.

  • Removing redundant path elements, such as ., .., //.

  • Following symbolic links.

  • Normalize non-existing path elements.

enumerator PhysicalNoFinalSymlink

Fully resolve the path but don’t follow the final symbolic link.

  • Requires the path to exist.

  • Removing redundant path elements, such as ., .., //.

  • Following symbolic links, except the final one. This is the mode used by FileInfo to resolve the path.

enumerator Physical

Fully resolve the path to its physical location.

  • Requires the path to exist.

  • Removing redundant path elements, such as ., .., //.

  • Following symbolic links.

class PathResolveOptions

Options for resolving paths.

Public Functions

PathResolveOptions() = default

Create path-resolve options with their default values.

inline PathResolveOptions(const PathResolveMode mode) noexcept

Create options from a resolve mode.

inline PathResolveMode mode() const noexcept

The mode for resolving paths.

inline PathResolveOptions &setMode(const PathResolveMode mode) noexcept

Set the mode for resolving paths.

class PathTempDirectoryOptions

Options for creating temporary directories.

Public Functions

PathTempDirectoryOptions()

Create the default options.

inline const text::String &prefix() const noexcept

The prefix to add in front of the random name part.

inline PathTempDirectoryOptions &setPrefix(const text::String &value)

Set the prefix to add in front of the random name part.

inline const text::String &suffix() const noexcept

The suffix to add after the random name part.

inline PathTempDirectoryOptions &setSuffix(const text::String &value)

Set the suffix to add after the random name part.

inline unit::CpLength randomLength() const noexcept

The number of random characters to place between prefix and suffix.

inline PathTempDirectoryOptions &setRandomLength(const unit::CpLength value) noexcept

Set the number of random characters to place between prefix and suffix.

inline unit::ItemCount maximumAttempts() const noexcept

The maximum number of generated names to try before giving up.

inline PathTempDirectoryOptions &setMaximumAttempts(const unit::ItemCount value) noexcept

Set the maximum number of generated names to try before giving up.

inline bool removeOnDestroy() const noexcept

Remove the directory recursively when the last temporary directory handle is destroyed.

inline PathTempDirectoryOptions &setRemoveOnDestroy(const bool value) noexcept

Set whether to remove the directory when the last temporary directory handle is destroyed.

inline PathAccessProfile accessProfile() const noexcept

The access profile for newly created temporary directories.

inline PathTempDirectoryOptions &setAccessProfile(const PathAccessProfile value) noexcept

Set the access profile for newly created temporary directories.

class PathTempFileOptions

Options for creating temporary files.

Public Functions

PathTempFileOptions()

Create the default options.

inline const text::String &prefix() const noexcept

The prefix to add in front of the random name part.

inline PathTempFileOptions &setPrefix(const text::String &value)

Set the prefix to add in front of the random name part.

inline const text::String &suffix() const noexcept

The suffix to add after the random name part.

inline PathTempFileOptions &setSuffix(const text::String &value)

Set the suffix to add after the random name part.

inline unit::CpLength randomLength() const noexcept

The number of random characters to place between prefix and suffix.

inline PathTempFileOptions &setRandomLength(const unit::CpLength value) noexcept

Set the number of random characters to place between prefix and suffix.

inline unit::ItemCount maximumAttempts() const noexcept

The maximum number of generated names to try before giving up.

inline PathTempFileOptions &setMaximumAttempts(const unit::ItemCount value) noexcept

Set the maximum number of generated names to try before giving up.

inline bool removeOnClose() const noexcept

Remove the file when the temporary stream is closed or destroyed.

inline PathTempFileOptions &setRemoveOnClose(const bool value) noexcept

Set whether to remove the file when the temporary stream is closed or destroyed.

inline PathAccessProfile accessProfile() const noexcept

The access profile for newly created temporary files.

inline PathTempFileOptions &setAccessProfile(const PathAccessProfile value) noexcept

Set the access profile for newly created temporary files.

enum class erbsland::path::PathType : std::uint8_t

The type of the resource behind a path.

Values:

enumerator Unknown

Cannot be determined, does not exist, or unsupported type.

enumerator Directory

Directory.

enumerator RegularFile

Regular file.

enumerator Symlink

Symbolic link to file or directory.

enumerator Device

Character/block device, Windows device, volume, console, etc.

enumerator Socket

Unix domain socket / Windows socket-like filesystem object if detectable.

enumerator Pipe

FIFO / named pipe.

enumerator ReparsePoint

Windows reparse point that is not a symlink.

enumerator All

All types.

enum class erbsland::path::PathWalkDirection : uint8_t

The direction for walking paths.

Values:

enumerator RootToLeaf

Walk from root to leaf.

All files and subdirectories of a directory are processed before descending into subdirectories.

enumerator LeafToRoot

Walk from leaf to root.

Processing the leaf files first, then processing the parent directories. At the time a directory is encountered, all its contents were processed before.

class PathWalker

Walk a path tree in a deterministic order.

Public Functions

PathWalker()

Create an empty/invalid path walker.

explicit PathWalker(const Path &path)

Create a path walker for the given path.

~PathWalker()

dtor

PathWalker &operator=(PathWalker&&) noexcept

Move path-walker state into this instance.

bool isEmpty() const

Test if the path is empty.

const Path &path() const

Access the underlying path.

PathWalkResult walk(const PathWalkFn &walkFn, PathWalkOptions options = {}) const

Walk all paths starting with this base path.

The base path is included. RootToLeaf reports a directory before its children, while LeafToRoot reports it after its children. Skip prevents descent in root-to-leaf order; in leaf-to-root order descent has already happened and Skip is equivalent to Continue.

Parameters:
  • walkFn – The walk function.

  • options – Options for the walk operation.

Returns:

The walk operation result.

PathWalkResult walk(const PathInfoWalkFn &walkFn, PathWalkOptions options = {}) const

Walk all paths starting with this base path with additional path info for each path.

This function may be faster, as file attributes can be pre-fetched.

Parameters:
  • walkFn – The walk function.

  • options – Options for the walk operation.

Returns:

The walk operation result.

PathWalkResult walkOrThrow(const PathWalkFn &walkFn, PathWalkOptions options = {}) const

Walk all paths starting with this base path.

The walk function returning the status Error is reported as an Error result, not throwing an exception.

Parameters:
  • walkFn – The walk function. Can throw an exception.

  • options – Options for the walk operation.

Throws:

PathError – if an error occurs during the walk operation and IgnoreErrors is not set.

Returns:

The walk operation result.

PathWalkResult walkOrThrow(const PathInfoWalkFn &walkFn, PathWalkOptions options = {}) const

Walk all paths starting with this base path with additional path info for each path.

This function may be faster, as file attributes can be pre-fetched. The walk function returning the status Error is reported as an Error result, not throwing an exception.

Parameters:
  • walkFn – The walk function. Can throw an exception.

  • options – Options for the walk operation.

Throws:

PathError – if an error occurs during the walk operation and IgnoreErrors is not set.

Returns:

The walk operation result.

using erbsland::path::PathWalkFn = std::function<PathWalkStatus(const Path&)>

The path walk callback.

using erbsland::path::PathInfoWalkFn = std::function<PathWalkStatus(const Path&, const PathInfo&)>

The path walk callback with additional path info for each path.

class PathWalkOptions

Options for the path walk function.

Public Functions

PathWalkOptions() = default

Create path-walk options with their default values.

inline bool ignoreErrors() const noexcept

If all errors should be ignored.

inline PathWalkOptions &setIgnoreErrors(const bool value) noexcept

Set if all errors should be ignored.

inline PathTypes types() const noexcept

The reported path types while walking.

If directories are not part of this set, they will still be scanned, but the walk function will not be called for them.

inline PathWalkOptions &setTypes(const PathTypes value) noexcept

Set the reported path types while walking.

inline SymlinkMode symlinkMode() const noexcept

How to handle symlinks.

inline PathWalkOptions &setSymlinkMode(const SymlinkMode value) noexcept

Set how to handle symlinks.

inline PathWalkDirection direction() const noexcept

The walk direction.

inline PathWalkOptions &setDirection(const PathWalkDirection value) noexcept

Set the walk direction.

inline PathInfoParts infoParts() const noexcept

The info parts to initially request and cache for a walk with path information.

inline PathWalkOptions &setInfoParts(const PathInfoParts value) noexcept

Set the info parts to initially request and cache for a walk with path information.

class PathWalkResult : public erbsland::util::Result

The result of a path walk call.

Public Functions

inline constexpr Result(const Value value)

Create a new result.

Parameters:

value – The value of the result.

Public Static Attributes

static const PathWalkResult Success = Value::success<0>()

Successfully completed the walk.

static const PathWalkResult Stopped = Value::success<1>()

The user early stopped the walk (successfully).

static const PathWalkResult Failure = Value::failure<0>()

The walk was stopped because of a failure.

enum class erbsland::path::PathWalkStatus : uint8_t

The returned status of a file walk function.

Values:

enumerator Continue

Continue with the next path.

enumerator Skip

Skip descent in root-to-leaf order; equivalent to Continue in leaf-to-root order.

enumerator Stop

Stop the walk.

enumerator Failure

Stop the walk because of a failure.

enum class erbsland::path::PathWindowsFormat : std::uint8_t

The format in which a Windows path is converted.

Values:

enumerator Native

Returns the path using backslash (\) path separators.

enumerator Extended

Returns the path using backslash (\) path separators as an extended length path.

This will add the Windows extended-length prefix for regular paths or UNC paths.

class PathWriteDataOptions

The options for writing data to a file.

Public Functions

PathWriteDataOptions() = default

Create the default options.

inline bool createParents() const noexcept

Create the parent directories if they do not exist.

inline PathWriteDataOptions &setCreateParents(const bool value) noexcept

Set whether to create the parent directories if they do not exist.

inline PathCreateMode creationMode() const noexcept

The creation mode for the file.

inline PathWriteDataOptions &setCreationMode(const PathCreateMode mode) noexcept

Set the creation mode for the file.

inline PathAccessProfile accessProfile() const noexcept

The access profile for newly created files.

inline PathWriteDataOptions &setAccessProfile(const PathAccessProfile value) noexcept

Set the access profile for newly created files.

inline time::TimeDelta timeout() const noexcept

Get the maximum wait for one stream operation.

inline PathWriteDataOptions &setTimeout(const time::TimeDelta value) noexcept

Set the maximum wait for one stream operation.

inline const stream::OutputStreamSettings &streamSettings() const noexcept

Get the stream settings.

inline PathWriteDataOptions &setStreamSettings(const stream::OutputStreamSettings &value) noexcept

Set the stream settings.

Public Static Attributes

static const auto cDefaultTimeout = time::TimeDelta::seconds(60)

The default timeout for whole-file path operations.

class PathWriteTextOptions

The options for writing text to a file.

Public Functions

PathWriteTextOptions() = default

Create the default options.

PathWriteTextOptions(text::StringEncoding encoding)

Use defaults with a different encoding.

Parameters:

encoding – The encoding to use.

inline bool createParents() const noexcept

Create the parent directories if they do not exist.

inline PathWriteTextOptions &setCreateParents(const bool value) noexcept

Set whether to create the parent directories if they do not exist.

inline PathCreateMode creationMode() const noexcept

The creation mode for the file.

inline PathWriteTextOptions &setCreationMode(const PathCreateMode mode) noexcept

Set the creation mode for the file.

inline PathAccessProfile accessProfile() const noexcept

The access profile for newly created files.

inline PathWriteTextOptions &setAccessProfile(const PathAccessProfile value) noexcept

Set the access profile for newly created files.

inline text::StringEncoding encoding() const noexcept

Get the text encoding.

inline PathWriteTextOptions &setEncoding(const text::StringEncoding value) noexcept

Set the text encoding.

inline text::StringBomMode bomMode() const noexcept

Get the byte-order-mark mode.

inline PathWriteTextOptions &setBomMode(const text::StringBomMode value) noexcept

Set the byte-order-mark mode.

inline time::TimeDelta timeout() const noexcept

Get the maximum wait for one stream operation.

inline PathWriteTextOptions &setTimeout(const time::TimeDelta value) noexcept

Set the maximum wait for one stream operation.

inline const stream::OutputStreamSettings &streamSettings() const noexcept

Get the stream settings.

inline PathWriteTextOptions &setStreamSettings(const stream::OutputStreamSettings &value) noexcept

Set the stream settings.

Public Static Attributes

static const auto cDefaultTimeout = time::TimeDelta::seconds(60)

The default timeout for whole-file path operations.

enum class erbsland::path::SymlinkMode : uint8_t

The mode to use when a symlink is detected for an operation.

Values:

enumerator Follow

Follow the symlink.

enumerator Skip

Skip any symlink.

enumerator Use

Use the symlink as it is (e.g., copy, access), do not follow it.

class TempDirectory

A shared temporary directory cleanup lease.

Temporary directory instances are intended to be created through PathOperations. The implementation will remove the directory recursively when the last shared handle is destroyed, unless release() was called or automatic cleanup was disabled.

Public Functions

TempDirectory() = default

Create an empty temporary directory handle.

~TempDirectory()

Destroy the temporary directory handle.

bool isEmpty() const noexcept

Test if this handle has no temporary directory path.

const Path &path() const noexcept

Access the temporary directory path.

bool removeOnDestroy() const noexcept

Test if the directory is removed when this handle is destroyed.

void setRemoveOnDestroy(bool value) noexcept

Set whether to remove the directory when this handle is destroyed.

Path release() noexcept

Disable automatic cleanup and return the directory path.

util::Result remove() noexcept

Remove the temporary directory now.

Returns:

Result::Success if the directory was removed, Result::Failure otherwise.

void removeOrThrow()

Remove the temporary directory now.

Throws:

PathError – if removing the directory failed.