System & concurrency

system.h

Simple functions for paths, files, environment variables, processes, and system information.

C++23 mc/system.h
#include <mc/system.h>

Path operations use the host filesystem conventions. Durations are in seconds unless a signature takes a std::chrono::duration; memory and file sizes are in bytes unless named otherwise.

Link Catalyst::Shared or Catalyst::Static for the compiled helpers. CTempFile and CTempDir remove owned resources on destruction; CSBuffer requires explicit closure.

Jump to a declaration · 116

Free functions & types

Types, constants & data

enum class CFileType { Missing, File, Directory, Symlink, Other };

Functions

cJoinPath

cstr cJoinPath(std::initializer_list<cstr> parts);
cstr cJoinPath(const cstr& first, const cstr& second);
template<class... Parts> requires(sizeof...(Parts) > 0) cstr cJoinPath(const cstr& first, const cstr& second, const Parts&... rest);

Joins path components with filesystem path semantics; an absolute component can replace the preceding path.

cAbsolutePath

cstr cAbsolutePath(const cstr& path, const cstr& base = "");

Resolves a relative path against base, or the current directory when base is empty.

cNormalizePath

cstr cNormalizePath(const cstr& path);

Normalizes . and .. lexically without requiring the path to exist.

cRelativePath

cstr cRelativePath(const cstr& path, const cstr& base = "");

Returns a lexical path from base to path, making both absolute first. An empty base uses the current directory; symbolic links are not resolved.

cExpandPath

cstr cExpandPath(const cstr& path);

Expands supported environment syntax and a leading home-directory marker.

cHasEnv

bool cHasEnv(const cstr& name);

Tests whether the process environment contains the variable, including one set to an empty string.

cEnv

cstr cEnv(const cstr& name, const cstr& fallback);
inline cstr cEnv(const cstr& name);

Returns the environment value. A missing variable gives an empty string, or the explicit fallback in the two-argument overload.

cUnsetEnv

void cUnsetEnv(const cstr& name);

Removes a variable from the current process environment. It does not change the parent shell’s environment.

cExpandEnvs

cstr cExpandEnvs(const cstr& text, bool strict = true);

Expands $NAME, ${NAME}, or $(NAME) once. A backslash escapes a dollar. Missing variables throw unless strict=false, which leaves them intact.

cStrToFile

void cStrToFile(const cstr& text, const cstr& path);

Writes the string’s bytes, replacing any existing file contents. Embedded NUL bytes are preserved.

cAppendToFile

void cAppendToFile(const cstr& text, const cstr& path);

Appends the string’s bytes, creating the file if necessary. No separator or newline is added automatically.

cFileToBuffer

CBuffer cFileToBuffer(const cstr& path);

Reads the complete file into an owning CBuffer. The returned bytes remain valid independently of the file.

cReadLines

CVector<cstr> cReadLines(const cstr& path);

Reads lines into a vector, removing LF and any immediately preceding CR. Blank lines are retained, and a final unterminated line is included; use cForEachLine() to avoid loading all lines at once.

cForEachLine

void cForEachLine(const cstr& path, const std::function<bool(const cstr&)>& visit);

Visits lines without LF or a preceding CR; return false to stop reading.

cSaveAtomic

void cSaveAtomic(const cstr& text, const cstr& path);
void cSaveAtomic(const CBuffer& buffer, const cstr& path);

Writes through a temporary sibling and atomically replaces the destination. The parent directory must exist.

cCreateDirs

bool cCreateDirs(const cstr& path);

Creates missing directories throughout the path. Returns true if creation occurred, or false if the directory already existed.

cCopyFile

void cCopyFile(const cstr& source, const cstr& destination, bool overwrite = false);

Copies a file’s contents to the destination. An existing destination is rejected unless overwrite is true; use cCopyTree() for directories.

cCopyTree

void cCopyTree(const cstr& source, const cstr& destination, bool overwrite = false);

Copies directory contents into the destination. Merges existing directories and preserves symlinks without following them; overwrite applies to leaf entries.

cRemove

bool cRemove(const cstr& path);

Removes a file or empty directory; returns false when it does not exist.

cRemoveTree

uint64_t cRemoveTree(const cstr& path);

Removes an entire tree and returns the number of removed entries.

cFileInfo

CFileInfo cFileInfo(const cstr& path, bool followSymlinks = false);

Returns metadata for a link itself unless followSymlinks=true. writeTime is Unix seconds and permissions holds POSIX permission bits.

cWalkDir

void cWalkDir(const cstr& root, const std::function<bool(const cstr&, const CFileInfo&)>& visit, const CWalkOptions& options = {});

Visits entries below the root; false stops the entire walk. When following links, each physical directory is traversed at most once.

cUserHome

cstr cUserHome();

Returns the current user’s home directory. Uses an absolute HOME environment value when available, otherwise the account’s home directory made absolute.

cTempDir

cstr cTempDir();

Returns the resolved system temporary-directory path. This locates the shared temporary directory; use cCreateTempDir() to create a new owned directory.

cExecutablePath

cstr cExecutablePath();

Returns the resolved path of the running executable, including symbolic-link resolution.

cConfigDir

cstr cConfigDir(const cstr& application = "");

Returns the user configuration location, optionally with one application-name component appended. Uses ~/Library/Application Support on macOS and an absolute XDG_CONFIG_HOME or ~/.config elsewhere; the directory is not created.

cCacheDir

cstr cCacheDir(const cstr& application = "");

Returns the user cache location, optionally with one application-name component appended. Uses ~/Library/Caches on macOS and an absolute XDG_CACHE_HOME or ~/.cache elsewhere; the directory is not created.

cDataDir

cstr cDataDir(const cstr& application = "");

Returns the user data location, optionally with one application-name component appended. Uses ~/Library/Application Support on macOS and an absolute XDG_DATA_HOME or ~/.local/share elsewhere; the directory is not created.

cCreateTempFile

CTempFile cCreateTempFile(const cstr& dir = "", const cstr& prefix = "catalyst-");

Creates an owned file with mode 0600. An empty directory selects cTempDir().

cCreateTempDir

CTempDir cCreateTempDir(const cstr& dir = "", const cstr& prefix = "catalyst-");

Creates an owned directory with mode 0700. An empty directory selects cTempDir().

cRun

CRunResult cRun(const CVector<cstr>& arguments, const cstr& input = "");

Executes an argument vector directly, supplies stdin, and captures both output streams. Nonzero exit status is returned; launch and I/O failures throw.

cRunShell

CRunResult cRunShell(const cstr& command, const cstr& input = "");

Runs a shell command, supplies stdin, and captures stdout and stderr. Shell quoting and expansion apply.

cFindExecutable

cstr cFindExecutable(const cstr& name);

Searches for an executable and returns an empty string if none is found.

cMonotonicNow

inline double cMonotonicNow();

Returns monotonic seconds for measuring intervals; the origin has no calendar meaning.

cElapsed

inline double cElapsed(double start);

Returns seconds elapsed since a cMonotonicNow() reading.

cHostName

cstr cHostName();

Returns the operating system’s complete hostname. Unlike the legacy cHost() helper, it preserves punctuation and domain components.

cDiskSpace

CDiskSpace cDiskSpace(const cstr& path = ".");

Returns filesystem capacity, free bytes, and bytes available to the current user for the given path. Reserved filesystem space can make available smaller than free.

cProcessMemory

CProcessMemory cProcessMemory();

Returns a snapshot of this process’s resident and virtual memory sizes in bytes. These measure different aspects of memory use and need not track one another.

cAvailableMemory

uint64_t cAvailableMemory();

Estimates system memory available for use, including reclaimable memory where the platform reports it. This is a changing snapshot, not a guarantee that an allocation will succeed.

cHost

inline cstr cHost();

Returns the initial alphanumeric part of the hostname. Use cHostName() for the full hostname.

cSetEnv

inline void cSetEnv(const cstr& name, const cstr& value, bool redefine = true);

Sets a variable in the process environment. With redefine=false, an existing value is retained; changes do not update the parent shell.

cProcessId

inline size_t cProcessId();

Returns the current process ID.

cSystemMemory

inline size_t cSystemMemory();

Returns the system’s physical memory size in bytes using the reported page count and page size.

cReplaceEnvs

inline void cReplaceEnvs(cstr& s);

Legacy in-place expansion of $(NAME). A missing variable is left in place with a warning.

cExists

inline bool cExists(const cstr& path);

Tests whether the path resolves to an existing filesystem object. Follows symbolic links, so a dangling link reports false.

cIsDir

inline bool cIsDir(const cstr& path);

Tests whether the path resolves to a directory, following symbolic links.

cIsFile

inline bool cIsFile(const cstr& path);

Tests whether the path resolves to a regular file, following symbolic links.

cBasename

inline cstr cBasename(const cstr& path);

Returns the final path component, including its extension.

cFilename

inline cstr cFilename(const cstr& path);

Returns the final component without its extension.

cParentDir

inline cstr cParentDir(const cstr& path);

Returns the lexical parent portion of a path. A bare filename has an empty parent; this does not inspect the filesystem.

cExtension

inline cstr cExtension(const cstr& path);

Returns the final filename extension without its leading dot, or an empty string if none exists.

cWriteTime

inline double cWriteTime(const cstr& path);

Returns the last modification time as approximate Unix seconds, converted from the filesystem clock.

cCurrentDir

inline cstr cCurrentDir();

Returns the process’s current working directory.

cDirFiles

template<class T = CVector<cstr>> inline T cDirFiles(const cstr& path);

Returns the names of all immediate directory entries, including hidden entries and subdirectories. Results are not sorted.

cFileSize

inline size_t cFileSize(const cstr& path);

Returns a regular file’s size in bytes. This does not recursively total directory contents.

cReadable

inline bool cReadable(const cstr& path);

Tests read access using the current process credentials. It is a preliminary snapshot; a later open can still fail.

cWritable

inline bool cWritable(const cstr& path);

Tests write access using the current process credentials. It does not create the path or ensure a later write will succeed.

cExecutable

inline bool cExecutable(const cstr& path);

Tests execute access using the current process credentials. On directories, this tests search permission rather than identifying a runnable program.

cTempPath

inline cstr cTempPath(const cstr& path, const cstr& suffix = "");

Produces a temporary-looking path string; it does not create or reserve the path.

cNow

inline double cNow();

Returns Unix wall-clock seconds.

cTicks

inline uint64_t cTicks();

Returns the high-resolution clock’s native tick count; do not assume seconds or nanoseconds.

cSleep

template<class R, class P> inline void cSleep(const std::chrono::duration<R, P>& dt);
inline void cSleep(double dt);
inline void cSleep();

Blocks the current thread for the supplied duration. The numeric overload uses seconds; scheduling may delay the thread beyond the requested interval.

cFileToStr

inline cstr cFileToStr(const cstr& path);

Reads the complete file into a string, preserving its bytes and line endings. Throws CError when the file cannot be opened or read.

cCreateDir

inline void cCreateDir(const cstr& path);

Creates one directory and throws if creation fails, including when it already exists. cCreateDirs() creates missing parents and tolerates existing directories.

cRename

inline void cRename(const cstr& oldPath, const cstr& newPath);

Renames or moves a filesystem entry using the platform’s rename semantics. Cross-filesystem moves can fail; this is not a copy-and-delete operation.

cThreadCount

inline size_t cThreadCount();

Returns the hardware concurrency hint, which can be zero if unavailable. This is not a count of currently running process threads.

cUId

inline cstr cUId();

Produces a clock-derived printable identifier; uniqueness is not guaranteed across processes.

cPause

inline void cPause();

Prints the process ID and sleeps for 30 seconds.

cSaveBinary

inline void cSaveBinary(char* buf, size_t bytes, const cstr& path);

Writes exactly the supplied byte range to a file, replacing existing contents. The caller retains ownership of the source memory.

CFileInfo

struct CFileInfo

Types, constants & data

CFileType type = CFileType::Missing;
uint64_t size = 0;
double writeTime = 0;
unsigned permissions = 0;

CWalkOptions

Types, constants & data

bool recursive = true;
bool hidden = false;

CTempFile

class CTempFile

Methods

CTempFile

CTempFile() = default;
CTempFile(const CTempFile&) = delete;
CTempFile(CTempFile&& other) noexcept;

Default construction creates an empty owner; use cCreateTempFile() to create the resource. Move construction transfers cleanup responsibility and leaves the source empty.

operator=

CTempFile& operator=(const CTempFile&) = delete;
CTempFile& operator=(CTempFile&& other) noexcept;

Move assignment first attempts to remove the currently owned file, then takes ownership from the source. Cleanup failures are suppressed because the operation is noexcept.

~CTempFile

~CTempFile();

Attempts to remove the owned file without throwing. Call remove() explicitly when cleanup failures must be reported.

path

const cstr& path() const;

Borrows the owned resource’s absolute path. It is empty after default construction, a move, release, or successful removal.

release

cstr release();

Relinquishes ownership and returns the path. The caller becomes responsible for removal.

remove

void remove();

Removes the owned resource now and clears ownership.

CTempDir

class CTempDir

Methods

CTempDir

CTempDir() = default;
CTempDir(const CTempDir&) = delete;
CTempDir(CTempDir&& other) noexcept;

Default construction creates an empty owner; use cCreateTempDir() to create the resource. Move construction transfers cleanup responsibility and leaves the source empty.

operator=

CTempDir& operator=(const CTempDir&) = delete;
CTempDir& operator=(CTempDir&& other) noexcept;

Move assignment first attempts to remove the currently owned directory tree, then takes ownership from the source. Cleanup failures are suppressed because the operation is noexcept.

~CTempDir

~CTempDir();

Attempts to remove the owned directory tree without throwing. Call remove() explicitly when cleanup failures must be reported.

path

const cstr& path() const;

Borrows the owned resource’s absolute path. It is empty after default construction, a move, release, or successful removal.

release

cstr release();

Relinquishes ownership and returns the path. The caller becomes responsible for removal.

remove

void remove();

Removes the owned resource now and clears ownership.

CRunResult

struct CRunResult

Types, constants & data

int status = 0;
cstr out;
cstr err;

CDiskSpace

struct CDiskSpace

Types, constants & data

uint64_t capacity = 0;
uint64_t free = 0;
uint64_t available = 0;

CProcessMemory

Types, constants & data

uint64_t resident = 0;
uint64_t virtualBytes = 0;

CSBuffer

class CSBuffer

Methods

create

template<CString T> void create(T&& path, size_t bytes);

Creates or resizes a shared backing file and maps the requested nonzero byte count read/write.

open

template<CString T> void open(T&& path, size_t bytes);

Maps an existing backing file, which must contain at least the requested bytes.

close

void close();

Unmaps the region. Copies are non-owning aliases: call once per mapping, after all aliases finish. Destruction does not close it.

path

const cstr& path() const;

Borrows the backing shared-memory name used by this mapping.

buffer

unsigned char* buffer() const;

Returns a borrowed writable pointer to the mapped bytes. All copies alias the same mapping; stop using them before close() unmaps it.

bytes

size_t bytes() const;

Returns the size of the shared-memory mapping in bytes.