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.

Path Equality and Ordering

Path::compare() and the comparison operators compare stored roots and then individual path components. They allocate no temporary strings or lists and do not access the filesystem. Empty paths sort first, an absent root sorts before a present root, and an equal component prefix sorts before its descendants. Within each root or component, the default comparison uses decoded, case-sensitive code-point order. An optional character comparator changes that character ordering without changing component boundaries.

Component ordering differs from serialized-text ordering: a/b precedes a-b, because the component a is a prefix of a-b. Format metadata and cached filesystem information do not affect comparison. Dot components remain lexical values: comparing a/./b with a/b does not resolve either path. Equal path values need not identify the same physical file, and different values may identify the same file through links or filesystem case rules. See Working with Paths for choosing value comparison versus filesystem operations.

Joining Paths

join() modifies the path; joined() returns a joined copy. Their string overloads and the / and /= operators parse text using the generic Path{text} constructor. In relative generic text, both slash and backslash are separators, including on POSIX systems.

Use joinNative() or joinedNative() for native filenames and path text. These methods parse the argument with Path::fromNative() before joining. For example, base.joinedNative(R"(a\b.txt)"_el) appends one filename containing a literal backslash on POSIX and two components on Windows.

All joining forms preserve the base path’s root and discard the appended path’s root. An empty base remains empty, and an argument that parses to an empty path leaves the base unchanged. Joining neither accesses the filesystem nor resolves dot components. Use the throwing native parser explicitly when malformed argument text must be reported.

Native Argument Text

Path::toString() exports portable path text, while Path::toNativeString() exports text for native command-line arguments. The native form uses POSIX spelling on POSIX hosts and backslashes with PathWindowsFormat::Native on Windows. It adds no shell quoting or escaping; pass the result as one Subprocess argument. As with the explicit format conversions, a path that cannot be represented in the selected native format produces an empty string.

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. Lexical normalization also shares that cache when the path has no dot components to normalize. Path conversions with an explicit absolute base do not query the process working directory. 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.

Filtering a Directory Walk

PathWalkOptions::setFilter() selects reported entries from their path and effective type before the walker requests additional infoParts(). An empty filter accepts all entries selected by types(). Rejected directories are still traversed. setDescendFilter() independently selects which directories to enter, including the starting directory, and applies before descent in either walk direction. A pruned directory can still be reported.

setGlobPattern() adds a compiled Path Glob Patterns filter, or compiles a supplied string and flags. It matches relative to the starting directory, which has zero relative components. Full matching is the default: *.cpp selects immediate children, while **/*.cpp includes deeper files. setGlobMatchMode(PathGlobMatchMode::Suffix) selects suffix matching instead.

Glob matching precedes the reporting filter and requested metadata. Descendant feasibility precedes the descent filter. Nonmatching ancestors remain traversable, while impossible branches reach neither callback. A null compiled pattern disables glob filtering. A compilation error leaves the previous option intact.

Both filters use PathWalkFilterFn. Symlink handling precedes filtering, so skipped links never reach either filter; followed links have their target type. Filters also apply to the starting path. They run synchronously and use the same exception handling as the walk callback. Name predicates can select extensions without requesting file sizes, ownership, or timestamps for rejected entries. Native enumeration and deterministic sorting still occur for visited directories.

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.

Replacing Content and Retaining Backups

PathContent::replaceTextOrThrow() and replaceDataOrThrow() write complete content into an exclusively created sibling temporary file. They finalize the output before replacing the destination with a native same-filesystem move. The destination can be absent or a regular file; symbolic links, reparse points, and other file types are rejected. There is no fallback that deletes the live destination or copies new content into it. The non-throwing forms return util::Result and intentionally discard diagnostic details.

auto options = el::PathReplaceTextOptions{}.setBackupCount(el::ItemCount{3U});
destination.content().replaceTextOrThrow(newText, options);

PathReplaceDataOptions and PathReplaceTextOptions provide output settings, a new-file access profile, and forwarding setters for PathCommitOptions. Text options also select the encoding and byte-order-mark policy. The default timeout is 60 seconds per stream operation. Parent creation and backups are disabled by default. Replacement uses the temporary file’s metadata; it does not preserve destination ownership, permissions, ACLs, or hard-link relationships. Flushing and native replacement do not promise portable crash durability.

backupCount retains that many overwritten versions beside the destination, excluding the current file. For report.txt, the newest backup is report.txt.bak.1, followed by report.txt.bak.2 and so on. Enabling backups reserves this naming scheme. Only canonical positive decimal generations representable as native size values are managed; names such as report.txt.bak.01 remain untouched. Reducing the count removes excess generations. Setting it to zero leaves all existing backups untouched. A new destination does not create a backup.

Backup copies use the UserOnly access profile to avoid exposing old content through broader default permissions. The old destination is copied through bounded byte transfers into a second sibling temporary file and finalized before backup rotation begins. Managed backup entries must be regular files, never links or reparse points. The live destination remains in place until the final replacement move. By default, a backup failure stops replacement. setIgnoreBackupErrors(true) makes backup preparation best effort: it suppresses backup failures and still attempts replacement. Destination validation, caller checks, and replacement failures are never suppressed by this setting.

Backup rotation and destination replacement are separate filesystem operations. A failed attempt may partly rotate backups or install a backup without replacing the destination. No rollback of backup history is promised. Collision checks and path validation are best effort under concurrent filesystem changes. Callers that need coordination can use the existing sidecar file lock around the entire operation.

Committing Temporary Output

TempByteOutputStream::commitToOrThrow() and TempTextOutputStream::commitToOrThrow() use the same replacement engine, accepting PathCommitOptions. Their non-throwing commitTo() forms return util::Result. A commit flushes and closes the backing stream without releasing its temporary file, then prepares requested backups and moves the temporary file into place. Only successful replacement releases cleanup ownership. Failed commits preserve the caller’s cleanup policy and support retry after finalization, including a close timeout. An empty or released temporary lease cannot be committed. Destruction never commits and never waits for cleanup.

The collision policy defaults to Overwrite; Stop is also supported, while Skip is rejected. An optional beforeCommit callback receives the absolute temporary and destination paths. It runs after finalization, before backup mutations, and again before the destination move when backup preparation was attempted. It must tolerate repeated calls and must not modify the temporary stream. A callback must report recoverable failures with err::RuntimeError or a derived type. These failures cancel the commit and are retained as diagnostic causes. Unexpected exceptions, including logic errors and allocation failures, propagate unchanged; they are never converted into replacement errors or ignored backup failures. The non-throwing status methods terminate on unexpected exceptions because they are noexcept.

Each failure reports its stage and relevant source and destination paths. Underlying stream exceptions, nested path exceptions, and native error details are preserved as causes. Render the complete chain with err::DiagnosticHelper instead of displaying only what(). Cleanup is best effort and never masks the original failure or claims that scheduled removal has already completed.

Portable Metadata Changes

PathOperations::setLastModified() changes a file or directory modification time through the native filesystem backend. The operation accepts PathChangeOptions, including its recursive and symbolic-link policy, invalidates cached path information after a successful change, and reports unrepresentable timestamps or native failures as PathError. The throwing setLastModifiedOrThrow() variant is suitable when preserving archive or copied-file timestamps is part of the operation’s correctness contract.

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 generic path text parsed using Path{other} (see joined).

Path &operator/=(const Path &other)

Join two paths (see join)

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

Join generic path text parsed using Path{other} (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.

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

Compare roots, then path components lexicographically without allocation or filesystem access.

Empty paths sort first, absent roots precede present roots, and equal prefixes precede descendants. Dot components are not resolved; format and cached metadata do not affect the result.

Parameters:
  • other – The other path for comparison.

  • compareFn – Optional decoded-character comparator within each root or component; case-sensitive by default.

Returns:

The component ordering, which may differ from ordering serialized paths.

See: File-System Paths

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.

  • String arguments use generic Path{other} parsing, including backslash separators in relative text.

  • 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 &joinNative(const text::String &other) noexcept

Append text parsed using the current platform’s native path syntax.

Equivalent to join(Path::fromNative(other)); preserves literal backslashes on POSIX. An empty parsed path leaves this path unchanged; an absolute suffix contributes only its non-root components.

Parameters:

other – Native path text, which may contain multiple components.

Returns:

This path after joining, without filesystem access.

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.

  • String arguments use generic Path{other} parsing, including backslash separators in relative text.

  • 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 joinedNative(const text::String &other) const noexcept

Return a copy with text appended using the current platform’s native path syntax.

Equivalent to joined(Path::fromNative(other)); follows the same joining rules as joinNative().

Parameters:

other – Native path text, which may contain multiple components.

Returns:

The joined path, leaving this path unchanged and without filesystem access.

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.

text::String toNativeString() const noexcept

Export a native path string suitable for command-line arguments on the current platform.

Returns:

POSIX spelling, or Windows spelling with native backslashes and no extended-path prefix.

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.

using erbsland::path::PathCommitCheckFn = std::function<void(const Path &temporary, const Path &destination)>

A synchronous, repeatable check before backup changes and the destination move.

class PathCommitOptions

Policies for committing a completed temporary file, optionally retaining overwritten content.

See: File-System Paths

Public Functions

inline PathCollisionMode collisionMode() const noexcept

Get the collision policy; only Stop and Overwrite are supported.

inline PathCommitOptions &setCollisionMode(PathCollisionMode value) noexcept

Set the collision policy.

inline bool createParents() const noexcept

Test whether missing destination parents are created.

inline PathCommitOptions &setCreateParents(bool value) noexcept

Set whether missing destination parents are created.

inline unit::ItemCount backupCount() const noexcept

Get the finite number of numbered backups; zero leaves all backups untouched.

inline PathCommitOptions &setBackupCount(unit::ItemCount value) noexcept

Set the number of backups to retain.

inline bool ignoreBackupErrors() const noexcept

Test whether backup failures are ignored while replacement is still attempted.

inline PathCommitOptions &setIgnoreBackupErrors(bool value) noexcept

Set whether to ignore errors in backup preparation only.

inline const PathCommitCheckFn &beforeCommit() const noexcept

Get the repeatable synchronous check, called after finalization and again after backup preparation.

inline PathCommitOptions &setBeforeCommit(PathCommitCheckFn value)

Set a check whose runtime failure cancels committing; it must not modify the temporary stream.

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. The file must not exceed the configured byte or code-point length limits.

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

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

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. The file must not exceed the configured maximum byte length.

Throws:

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

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.)

auto replaceText(const text::String &text, PathReplaceTextOptions options = {}) const noexcept -> util::Result

Replace complete text content through a sibling temporary file.

Parameters:
  • text – The complete replacement content.

  • options – The replacement and backup policies.

Returns:

Success after replacement, or Failure on any error.

void replaceTextOrThrow(const text::String &text, PathReplaceTextOptions options = {}) const

Replace complete text content through a sibling temporary file.

Parameters:
  • text – The complete replacement content.

  • options – The replacement and backup policies.

Throws:

PathError – If any replacement stage fails, retaining its original cause.

See: File-System Paths

auto replaceData(const mem::ByteBlock &data, PathReplaceDataOptions options = {}) const noexcept -> util::Result

Replace complete data content through a sibling temporary file.

Parameters:
  • data – The complete replacement content.

  • options – The replacement and backup policies.

Returns:

Success after replacement, or Failure on any error.

void replaceDataOrThrow(const mem::ByteBlock &data, PathReplaceDataOptions options = {}) const

Replace complete data content through a sibling temporary file.

Parameters:
  • data – The complete replacement content.

  • options – The replacement and backup policies.

Throws:

PathError – If any replacement stage fails, retaining its original cause.

See: File-System Paths

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 Timestamp::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::ByteCount 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::Timestamp 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::Timestamp 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::Timestamp 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::Timestamp 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::Timestamp 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.

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

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.

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

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 setLastModified(const time::Timestamp &value, PathChangeOptions options = {}) const noexcept

Set the last-modification time for this path.

Parameters:
  • value – The new modification time.

  • options – Options for the operation.

Returns:

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

void setLastModifiedOrThrow(const time::Timestamp &value, PathChangeOptions options = {}) const

Set the last-modification time for this path.

Parameters:
  • value – The new modification time.

  • options – Options for the operation.

Throws:

PathError – if the time is invalid or 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::ByteCount maximumByteLength() const noexcept

Get the maximum number of bytes to read.

inline PathReadDataOptions &setMaximumByteLength(const unit::ByteCount 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::ByteCount{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::ByteCount maximumByteLength)

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

Parameters:

maximumByteLength – The maximum byte length to read.

PathReadTextOptions(unit::CpCount 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::ByteCount maximumByteLength() const

Get the maximum number of bytes to read.

PathReadTextOptions &setMaximumByteLength(unit::ByteCount value)

Set the maximum number of bytes to read.

inline unit::CpCount maximumCpLength() const

Get the maximum number of code points to read.

PathReadTextOptions &setMaximumCpLength(unit::CpCount 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).

class PathReplaceDataOptions

Options for replacing complete data content using a sibling temporary file.

Public Functions

inline const PathCommitOptions &commitOptions() const noexcept

Get the common commit policies.

inline PathReplaceDataOptions &setCommitOptions(PathCommitOptions value)

Set the common commit policies.

inline PathCollisionMode collisionMode() const noexcept

Get the destination collision policy.

inline PathReplaceDataOptions &setCollisionMode(PathCollisionMode value) noexcept

Set the destination collision policy.

inline bool createParents() const noexcept

Test whether missing destination parents are created.

inline PathReplaceDataOptions &setCreateParents(bool value) noexcept

Set whether missing destination parents are created.

inline unit::ItemCount backupCount() const noexcept

Get the number of retained backups; zero leaves backups untouched.

inline PathReplaceDataOptions &setBackupCount(unit::ItemCount value) noexcept

Set the finite number of numbered backups to retain.

inline bool ignoreBackupErrors() const noexcept

Test whether backup preparation failures are ignored.

inline PathReplaceDataOptions &setIgnoreBackupErrors(bool value) noexcept

Set whether to ignore backup preparation failures only.

inline const PathCommitCheckFn &beforeCommit() const noexcept

Get the repeatable synchronous pre-commit check.

inline PathReplaceDataOptions &setBeforeCommit(PathCommitCheckFn value)

Set the repeatable synchronous pre-commit check.

inline PathAccessProfile accessProfile() const noexcept

Get the access profile applied to the new file.

inline PathReplaceDataOptions &setAccessProfile(PathAccessProfile value) noexcept

Set the access profile applied to the new file.

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

Get settings for the owned output stream.

inline PathReplaceDataOptions &setStreamSettings(stream::OutputStreamSettings value) noexcept

Set settings for the owned output stream.

inline time::TimeDelta timeout() const noexcept

Get the maximum wait for one stream operation.

inline PathReplaceDataOptions &setTimeout(time::TimeDelta value) noexcept

Set the maximum wait for one stream operation.

Public Static Attributes

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

The default maximum wait for each stream operation.

class PathReplaceTextOptions

Options for replacing complete text content using a sibling temporary file.

Public Functions

inline const PathCommitOptions &commitOptions() const noexcept

Get the common commit policies.

inline PathReplaceTextOptions &setCommitOptions(PathCommitOptions value)

Set the common commit policies.

inline PathCollisionMode collisionMode() const noexcept

Get the destination collision policy.

inline PathReplaceTextOptions &setCollisionMode(PathCollisionMode value) noexcept

Set the destination collision policy.

inline bool createParents() const noexcept

Test whether missing destination parents are created.

inline PathReplaceTextOptions &setCreateParents(bool value) noexcept

Set whether missing destination parents are created.

inline unit::ItemCount backupCount() const noexcept

Get the number of retained backups; zero leaves backups untouched.

inline PathReplaceTextOptions &setBackupCount(unit::ItemCount value) noexcept

Set the finite number of numbered backups to retain.

inline bool ignoreBackupErrors() const noexcept

Test whether backup preparation failures are ignored.

inline PathReplaceTextOptions &setIgnoreBackupErrors(bool value) noexcept

Set whether to ignore backup preparation failures only.

inline const PathCommitCheckFn &beforeCommit() const noexcept

Get the repeatable synchronous pre-commit check.

inline PathReplaceTextOptions &setBeforeCommit(PathCommitCheckFn value)

Set the repeatable synchronous pre-commit check.

inline PathAccessProfile accessProfile() const noexcept

Get the access profile applied to the new file.

inline PathReplaceTextOptions &setAccessProfile(PathAccessProfile value) noexcept

Set the access profile applied to the new file.

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

Get settings for the owned output stream.

inline PathReplaceTextOptions &setStreamSettings(stream::OutputStreamSettings value) noexcept

Set settings for the owned output stream.

inline time::TimeDelta timeout() const noexcept

Get the maximum wait for one stream operation.

inline PathReplaceTextOptions &setTimeout(time::TimeDelta value) noexcept

Set the maximum wait for one stream operation.

inline text::StringEncoding encoding() const noexcept

Get the text encoding policy.

inline PathReplaceTextOptions &setEncoding(text::StringEncoding value) noexcept

Set the text encoding policy.

inline text::StringBomMode bomMode() const noexcept

Get the byte-order-mark policy.

inline PathReplaceTextOptions &setBomMode(text::StringBomMode value) noexcept

Set the byte-order-mark policy.

Public Static Attributes

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

The default maximum wait for each stream operation.

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::CpCount randomLength() const noexcept

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

inline PathTempDirectoryOptions &setRandomLength(const unit::CpCount 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

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

Get output settings for temporary byte streams.

inline PathTempFileOptions &setStreamSettings(stream::OutputStreamSettings value)

Set output settings for temporary byte streams.

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::CpCount randomLength() const noexcept

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

inline PathTempFileOptions &setRandomLength(const unit::CpCount 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.

using erbsland::path::PathWalkFilterFn = std::function<bool(const Path&, PathType)>

Select a walk entry from its path and effective type, before requesting additional metadata.

class PathWalkOptions

Options for the path walk function.

Public Functions

PathWalkOptions() = default

Create path-walk options with their default values.

inline const PathGlobPatternPtr &globPattern() const noexcept

Get the optional glob selecting paths relative to the walk’s starting directory.

Returns:

The compiled glob, or null when glob filtering is disabled.

inline PathWalkOptions &setGlobPattern(PathGlobPatternPtr pattern) noexcept

Set a compiled reporting and descent glob; null disables glob filtering.

Parameters:

pattern – Immutable glob selecting reporting and feasible descendant paths.

Returns:

These options.

inline auto setGlobPattern(const text::String &pattern, PathGlobPatternFlags flags = PathGlobPatternFlag::Default) -> PathWalkOptions&

Compile and set a glob without changing the matching mode.

Parameters:
  • pattern – Pattern text, matched relative to the starting directory.

  • flags – Compile syntax; explicit flags replace defaults.

Throws:
Returns:

These options; compilation failure leaves the previous pattern intact.

inline PathGlobMatchMode globMatchMode() const noexcept

Get the glob matching mode; full matching is the default.

Returns:

The mode applied to relative paths.

inline PathWalkOptions &setGlobMatchMode(PathGlobMatchMode mode) noexcept

Select full or suffix glob matching.

Parameters:

mode – Matching mode for reporting and descendant feasibility.

Returns:

These options.

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 request and cache for entries accepted by the reporting filter.

inline PathWalkOptions &setInfoParts(const PathInfoParts value) noexcept

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

inline const PathWalkFilterFn &filter() const noexcept

The optional reporting filter; an empty callback accepts every entry matching types().

inline PathWalkOptions &setFilter(PathWalkFilterFn value)

Set a reporting filter applied to the root and children before requesting infoParts().

Rejected directories are still traversed. The type reflects the selected symlink policy.

inline const PathWalkFilterFn &descendFilter() const noexcept

The optional descent filter; an empty callback allows traversal into every directory.

inline PathWalkOptions &setDescendFilter(PathWalkFilterFn value)

Set a filter deciding whether to enter a directory, independently of reporting and direction().

It receives the root and each child directory with its effective Directory type.

class PathWalkResult : public erbsland::util::Result

The result of a path walk call.

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.