solidc
Robust collection of general-purpose cross-platform C libraries and data structures designed for rapid and safe development in C
Loading...
Searching...
No Matches
Classes | Macros | Typedefs | Enumerations | Functions
filepath.h File Reference

Cross-platform file path manipulation and directory traversal utilities. More...

#include "file.h"
#include "macros.h"
#include "platform.h"
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <dirent.h>
#include <pwd.h>
#include <sys/mman.h>
#include <sys/random.h>
#include <sys/stat.h>
#include <unistd.h>
Include dependency graph for filepath.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

struct  Directory
 

Macros

#define PATH_SEP   '/'
 
#define PATH_SEP_STR   "/"
 

Typedefs

typedef enum WalkDirOption WalkDirOption
 
typedef WalkDirOption(* WalkDirCallback) (const FileAttributes *attr, const char *path, const char *name, void *data)
 

Enumerations

enum  WalkDirOption { DirContinue , DirStop , DirSkip , DirError }
 

Functions

WARN_UNUSED_RESULT Directorydir_open (const char *path)
 
void dir_close (Directory *dir)
 
WARN_UNUSED_RESULT char * dir_next (Directory *dir)
 
int dir_create (const char *path)
 
int dir_remove (const char *path, bool recursive)
 
int dir_rename (const char *oldpath, const char *newpath)
 
int dir_chdir (const char *path)
 
WARN_UNUSED_RESULT char ** dir_list (const char *path, size_t *count)
 
void dir_list_with_callback (const char *path, void(*callback)(const char *name))
 
bool is_dir (const char *path)
 
bool is_file (const char *path)
 
bool is_symlink (const char *path)
 
bool filepath_makedirs (const char *path)
 
WARN_UNUSED_RESULT char * get_tempdir (void)
 
WARN_UNUSED_RESULT char * make_tempfile (void)
 
WARN_UNUSED_RESULT char * make_tempdir (void)
 
int dir_walk (const char *path, WalkDirCallback callback, void *data)
 
int dir_walk_depth_first (const char *path, WalkDirCallback callback, void *data)
 
ssize_t dir_size (const char *path)
 
bool path_exists (const char *path)
 
WARN_UNUSED_RESULT char * get_cwd (void)
 
void filepath_basename (const char *path, char *basename, size_t size)
 
void filepath_dirname (const char *path, char *dirname, size_t size)
 
void filepath_extension (const char *path, char *ext, size_t size)
 
void filepath_nameonly (const char *path, char *name, size_t size)
 
WARN_UNUSED_RESULT char * filepath_absolute (const char *path)
 
int filepath_remove (const char *path)
 
int filepath_rename (const char *oldpath, const char *newpath)
 
const char * user_home_dir (void)
 
WARN_UNUSED_RESULT char * filepath_expanduser (const char *path)
 
bool filepath_expanduser_buf (const char *path, char *expanded, size_t len)
 
WARN_UNUSED_RESULT char * filepath_join (const char *path1, const char *path2)
 
bool filepath_join_buf (const char *path1, const char *path2, char *abspath, size_t len)
 
void filepath_split (const char *path, char *dir, char *name, size_t dir_size, size_t name_size)
 

Detailed Description

Cross-platform file path manipulation and directory traversal utilities.

This module provides a unified API for file system operations across Windows and POSIX platforms. All functions handle path separators appropriately for the target platform.

Thread Safety: Individual functions document their thread-safety guarantees. Most functions are thread-safe unless otherwise noted.

Definition in file filepath.h.

Macro Definition Documentation

◆ PATH_SEP

#define PATH_SEP   '/'

Platform-specific directory separator character.

Definition at line 44 of file filepath.h.

◆ PATH_SEP_STR

#define PATH_SEP_STR   "/"

Platform-specific directory separator string.

Definition at line 47 of file filepath.h.

Typedef Documentation

◆ WalkDirCallback

typedef WalkDirOption(* WalkDirCallback) (const FileAttributes *attr, const char *path, const char *name, void *data)

Callback function type for directory walking.

Parameters
attrFile attributes of the current entry. Never NULL.
pathFull path to the entry. Valid only during callback invocation.
nameBasename of the entry. Valid only during callback invocation.
dataUser-provided context pointer passed to dir_walk.
Returns
WalkDirOption to control traversal behavior.
Note
Callback must not call dir_walk on the same path to avoid infinite recursion.

Definition at line 263 of file filepath.h.

◆ WalkDirOption

Control options for directory traversal callbacks.

Enumeration Type Documentation

◆ WalkDirOption

Control options for directory traversal callbacks.

Enumerator
DirContinue 

Continue walking the directory recursively.

DirStop 

Stop traversal immediately and return from dir_walk.

DirSkip 

Skip the current entry and its children (if directory).

DirError 

An error occurred; stop traversal and return error.

Definition at line 246 of file filepath.h.

Function Documentation

◆ dir_chdir()

int dir_chdir ( const char *  path)

Changes the current working directory of the process.

Parameters
pathPath to the new working directory. Must not be NULL.
Returns
0 on success, -1 on error (sets errno).
Note
Affects the entire process, not thread-local.
Not safe for concurrent use in multi-threaded programs.

Definition at line 498 of file filepath.c.

◆ dir_close()

void dir_close ( Directory dir)

Closes a directory handle and releases all associated resources.

Parameters
dirDirectory handle to close. Safe to pass NULL.
Note
Thread-safe with respect to other directories.

Definition at line 175 of file filepath.c.

References Directory::dir, dir_close(), and Directory::path.

Referenced by dir_close(), dir_list(), dir_list_with_callback(), dir_walk(), and dir_walk_depth_first().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ dir_create()

int dir_create ( const char *  path)

Creates a new directory with default permissions.

Parameters
pathPath of the directory to create. Must not be NULL.
Returns
0 on success (or if directory already exists), -1 on error (sets errno).
Note
On POSIX, creates with mode 0755. On Windows, uses default ACLs.
Does not create parent directories (use filepath_makedirs() for that).
Thread-safe.

Definition at line 306 of file filepath.c.

Referenced by filepath_makedirs().

Here is the caller graph for this function:

◆ dir_list()

WARN_UNUSED_RESULT char ** dir_list ( const char *  path,
size_t *  count 
)

Lists all entries in a directory.

Parameters
pathPath to the directory. Must not be NULL.
countPointer to store the number of entries. Must not be NULL.
Returns
Array of dynamically allocated entry names, or NULL on error (sets errno).
Note
Caller must free each entry string and the array itself.
Includes "." and ".." entries.
Thread-safe.

Definition at line 507 of file filepath.c.

References dir_close(), dir_next(), and dir_open().

Here is the call graph for this function:

◆ dir_list_with_callback()

void dir_list_with_callback ( const char *  path,
void(*)(const char *name)  callback 
)

Iterates directory entries with a callback function.

Parameters
pathPath to the directory. Must not be NULL.
callbackFunction called for each entry (excluding "." and ".."). Must not be NULL.
Note
Callback receives the entry name. The pointer is valid only during the callback.
Thread-safe if callback is thread-safe.

Definition at line 563 of file filepath.c.

References dir_close(), dir_next(), and dir_open().

Here is the call graph for this function:

◆ dir_next()

WARN_UNUSED_RESULT char * dir_next ( Directory dir)

Reads the next entry in the directory.

Parameters
dirDirectory handle returned by dir_open(). Must not be NULL.
Returns
Pointer to entry name, or NULL when no more entries or on error.
Note
The returned pointer is valid only until the next call to dir_next() or dir_close() on the same handle.
Special entries "." and ".." are included in iteration.
Not thread-safe: Do not call on the same handle from multiple threads.

Definition at line 192 of file filepath.c.

References Directory::dir, and dir_next().

Referenced by dir_list(), dir_list_with_callback(), and dir_next().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ dir_open()

WARN_UNUSED_RESULT Directory * dir_open ( const char *  path)

Opens a directory for reading.

Parameters
pathPath to the directory to open. Must not be NULL or empty.
Returns
Directory handle on success, NULL on failure (sets errno).
Note
Caller must call dir_close() to release resources.
Thread-safe: Each call returns an independent handle.

Definition at line 118 of file filepath.c.

References Directory::dir, dir_open(), and Directory::path.

Referenced by dir_list(), dir_list_with_callback(), dir_open(), dir_walk(), and dir_walk_depth_first().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ dir_remove()

int dir_remove ( const char *  path,
bool  recursive 
)

Removes a directory.

Parameters
pathPath to the directory to remove. Must not be NULL.
recursiveIf true, recursively removes all contents. If false, fails on non-empty directories.
Returns
0 on success, -1 on error (sets errno).
Note
Recursive removal uses depth-first post-order traversal.
Not safe for concurrent modification of the same directory tree.

Definition at line 473 of file filepath.c.

References dir_walk_depth_first().

Here is the call graph for this function:

◆ dir_rename()

int dir_rename ( const char *  oldpath,
const char *  newpath 
)

Renames or moves a directory.

Parameters
oldpathCurrent path of the directory. Must not be NULL.
newpathNew path for the directory. Must not be NULL.
Returns
0 on success, -1 on error (sets errno).
Note
Behavior is platform-specific when newpath exists.
May fail if oldpath and newpath are on different filesystems.
Thread-safe.

Definition at line 489 of file filepath.c.

◆ dir_size()

ssize_t dir_size ( const char *  path)

Calculates the total size of all files in a directory tree.

Parameters
pathRoot directory to measure. Must not be NULL.
Returns
Total size in bytes on success, -1 on error (sets errno).
Note
Walks the entire tree recursively; may be slow for large directories.
Only counts regular files, not directory metadata.
Thread-safe, but result may be stale in actively modified directories.

Definition at line 753 of file filepath.c.

References dir_walk().

Referenced by filepath_split().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ dir_walk()

int dir_walk ( const char *  path,
WalkDirCallback  callback,
void *  data 
)

Walks a directory tree in breadth-first order.

Parameters
pathRoot directory to walk. Must not be NULL.
callbackFunction called for each entry. Must not be NULL.
dataUser context pointer passed to callback. May be NULL.
Returns
0 on success, -1 on error (sets errno).
Note
Entries "." and ".." are automatically skipped.
Callback is invoked before recursing into subdirectories.
Not safe for concurrent modification of the traversed tree.

Recursively walks a directory tree, invoking a callback for each entry.

Parameters
pathStarting directory path.
callbackFunction to call for each directory entry.
dataUser-provided data passed to callback.
Returns
0 on success, -1 on error (errno is set).

Definition at line 649 of file filepath.c.

References FileAttributes::attrs, Directory::dir, dir_close(), dir_open(), dir_walk(), DirError, DirSkip, DirStop, FATTR_NONE, filepath_join_buf(), and populate_file_attrs().

Referenced by dir_size(), and dir_walk().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ dir_walk_depth_first()

int dir_walk_depth_first ( const char *  path,
WalkDirCallback  callback,
void *  data 
)

Walks a directory tree in depth-first post-order.

Parameters
pathRoot directory to walk. Must not be NULL.
callbackFunction called for each entry. Must not be NULL.
dataUser context pointer passed to callback. May be NULL.
Returns
0 on success, -1 on error (sets errno).
Note
Callback is invoked AFTER recursing into subdirectories.
Suitable for operations like recursive deletion.
Not safe for concurrent modification of the traversed tree.

Recursively walks a directory tree depth-first (post-order), invoking a callback for each entry. Files are processed before their containing directories. Useful for operations like deletion where you need to empty a directory before removing it.

Parameters
pathStarting directory path.
callbackFunction to call for each directory entry.
dataUser-provided data passed to callback.
Returns
0 on success, -1 on error (errno is set).

Definition at line 398 of file filepath.c.

References FileAttributes::attrs, Directory::dir, dir_close(), dir_open(), dir_walk_depth_first(), DirError, DirStop, FATTR_NONE, filepath_join_buf(), and populate_file_attrs().

Referenced by dir_remove(), and dir_walk_depth_first().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ filepath_absolute()

WARN_UNUSED_RESULT char * filepath_absolute ( const char *  path)

Converts a path to an absolute path.

Parameters
pathPath to convert (may be relative or absolute). Must not be NULL.
Returns
Dynamically allocated absolute path, or NULL on error (sets errno).
Note
Resolves ".", "..", and symbolic links (on POSIX).
Caller must free the returned string.
Thread-safe.

Definition at line 1015 of file filepath.c.

◆ filepath_basename()

void filepath_basename ( const char *  path,
char *  basename,
size_t  size 
)

Extracts the basename (filename with extension) from a path.

Parameters
pathFull path to parse. Must not be NULL.
basenameBuffer to store the result. Must not be NULL.
sizeSize of the basename buffer.
Note
Handles both forward and backslashes as separators.
If path ends with a separator, returns empty string.
Thread-safe.

Definition at line 948 of file filepath.c.

Referenced by filepath_nameonly().

Here is the caller graph for this function:

◆ filepath_dirname()

void filepath_dirname ( const char *  path,
char *  dirname,
size_t  size 
)

Extracts the directory portion of a path.

Parameters
pathFull path to parse. Must not be NULL.
dirnameBuffer to store the result. Must not be NULL.
sizeSize of the dirname buffer.
Note
Returns empty string if path has no directory component.
Does not include trailing separator.
Thread-safe.

Definition at line 963 of file filepath.c.

◆ filepath_expanduser()

WARN_UNUSED_RESULT char * filepath_expanduser ( const char *  path)

Expands tilde (~) in a path to the user's home directory.

Parameters
pathPath potentially starting with ~. Must not be NULL.
Returns
Dynamically allocated expanded path, or NULL on error.
Note
Only expands leading ~, not embedded tildes.
Returns copy of path unchanged if it doesn't start with ~.
Caller must free the returned string.
Thread-safe.

Definition at line 1079 of file filepath.c.

References PATH_SEP, and user_home_dir().

Here is the call graph for this function:

◆ filepath_expanduser_buf()

bool filepath_expanduser_buf ( const char *  path,
char *  expanded,
size_t  len 
)

Expands tilde (~) in a path to the user's home directory into a buffer.

Parameters
pathPath potentially starting with ~. Must not be NULL.
expandedBuffer to store the expanded path. Must not be NULL.
lenSize of the expanded buffer.
Returns
true on success, false if buffer too small or home directory not found.
Note
Thread-safe.

Definition at line 1118 of file filepath.c.

References user_home_dir().

Here is the call graph for this function:

◆ filepath_extension()

void filepath_extension ( const char *  path,
char *  ext,
size_t  size 
)

Extracts the file extension including the leading dot.

Parameters
pathFull path to parse. Must not be NULL.
extBuffer to store the result. Must not be NULL.
sizeSize of the ext buffer.
Note
Returns empty string if no extension exists.
Extension includes the dot (e.g., ".txt").
Thread-safe.

Definition at line 982 of file filepath.c.

◆ filepath_join()

WARN_UNUSED_RESULT char * filepath_join ( const char *  path1,
const char *  path2 
)

Joins two path components with the platform-specific separator.

Parameters
path1First path component. Must not be NULL.
path2Second path component. Must not be NULL.
Returns
Dynamically allocated joined path, or NULL on error (sets errno).
Note
Uses backslash on Windows, forward slash on POSIX.
Caller must free the returned string.
Thread-safe.

Definition at line 1156 of file filepath.c.

Referenced by make_tempdir(), and make_tempfile().

Here is the caller graph for this function:

◆ filepath_join_buf()

bool filepath_join_buf ( const char *  path1,
const char *  path2,
char *  abspath,
size_t  len 
)

Joins two path components into a provided buffer.

Parameters
path1First path component. Must not be NULL.
path2Second path component. Must not be NULL.
abspathBuffer to store the result. Must not be NULL.
lenSize of the abspath buffer.
Returns
true on success, false if buffer too small.
Note
Thread-safe.

Definition at line 1177 of file filepath.c.

Referenced by dir_walk(), and dir_walk_depth_first().

Here is the caller graph for this function:

◆ filepath_makedirs()

bool filepath_makedirs ( const char *  path)

Creates a directory and all necessary parent directories.

Parameters
pathPath to create. Must not be NULL.
Returns
true on success (or if path already exists), false on error.
Note
Similar to mkdir -p on Unix.
Thread-safe, but race conditions may occur with concurrent creation.

Definition at line 767 of file filepath.c.

References dir_create().

Here is the call graph for this function:

◆ filepath_nameonly()

void filepath_nameonly ( const char *  path,
char *  name,
size_t  size 
)

Extracts the filename without extension.

Parameters
pathFull path to parse. Must not be NULL.
nameBuffer to store the result. Must not be NULL.
sizeSize of the name buffer.
Note
Returns the basename with the extension removed.
Thread-safe.

Definition at line 995 of file filepath.c.

References filepath_basename().

Here is the call graph for this function:

◆ filepath_remove()

int filepath_remove ( const char *  path)

Deletes a file or empty directory.

Parameters
pathPath to remove. Must not be NULL.
Returns
0 on success, -1 on error (sets errno).
Note
Fails on non-empty directories (use dir_remove with recursive=true).
Thread-safe.

Definition at line 1047 of file filepath.c.

◆ filepath_rename()

int filepath_rename ( const char *  oldpath,
const char *  newpath 
)

Renames or moves a file or directory.

Parameters
oldpathCurrent path. Must not be NULL.
newpathNew path. Must not be NULL.
Returns
0 on success, -1 on error (sets errno).
Note
May fail if paths are on different filesystems.
Behavior when newpath exists is platform-specific.
Thread-safe.

Definition at line 1061 of file filepath.c.

◆ filepath_split()

void filepath_split ( const char *  path,
char *  dir,
char *  name,
size_t  dir_size,
size_t  name_size 
)

Splits a file path into directory and basename components.

Parameters
pathPath to split. Must not be NULL.
dirBuffer to store the directory portion. Must not be NULL.
nameBuffer to store the basename. Must not be NULL.
dir_sizeSize of the dir buffer.
name_sizeSize of the name buffer.
Note
If path has no directory, dir is set to empty string.
Thread-safe.

Definition at line 1204 of file filepath.c.

References dir_size().

Here is the call graph for this function:

◆ get_cwd()

WARN_UNUSED_RESULT char * get_cwd ( void  )

Returns the current working directory path.

Returns
Dynamically allocated path string, or NULL on error (sets errno).
Note
Caller must free the returned string.
Thread-safe.

Definition at line 1037 of file filepath.c.

◆ get_tempdir()

WARN_UNUSED_RESULT char * get_tempdir ( void  )

Returns the path to the system's temporary directory.

Returns
Dynamically allocated path string, or NULL on error.
Note
On Windows, checks TEMP, then TMP environment variables, falls back to C:\Windows\Temp.
On POSIX, checks TMPDIR environment variable, falls back to /tmp.
Caller must free the returned string.
Thread-safe.

Definition at line 809 of file filepath.c.

References GETENV.

Referenced by make_tempdir(), and make_tempfile().

Here is the caller graph for this function:

◆ is_dir()

bool is_dir ( const char *  path)

Checks if a path refers to a directory.

Parameters
pathPath to check. Must not be NULL.
Returns
true if path exists and is a directory, false otherwise.
Note
Follows symbolic links.
Thread-safe.

Definition at line 583 of file filepath.c.

◆ is_file()

bool is_file ( const char *  path)

Checks if a path refers to a regular file.

Parameters
pathPath to check. Must not be NULL.
Returns
true if path exists and is a regular file, false otherwise.
Note
Follows symbolic links.
Thread-safe.

Definition at line 604 of file filepath.c.

◆ is_symlink()

bool is_symlink ( const char *  path)

Checks if a path is a symbolic link.

Parameters
pathPath to check. Must not be NULL.
Returns
true if path is a symbolic link (POSIX only), false otherwise or on Windows.
Note
Does not follow symbolic links (uses lstat on POSIX).
Always returns false on Windows.
Thread-safe.

Definition at line 625 of file filepath.c.

◆ make_tempdir()

WARN_UNUSED_RESULT char * make_tempdir ( void  )

Creates a temporary directory with a unique name.

Returns
Dynamically allocated path to the created directory, or NULL on error (sets errno).
Note
Directory is created with default permissions.
Caller is responsible for removing the directory and freeing the path.
Thread-safe.

Definition at line 887 of file filepath.c.

References filepath_join(), and get_tempdir().

Here is the call graph for this function:

◆ make_tempfile()

WARN_UNUSED_RESULT char * make_tempfile ( void  )

Creates a temporary file with a unique name.

Returns
Dynamically allocated path to the created file, or NULL on error (sets errno).
Note
File is created with restrictive permissions (0600 on POSIX).
Caller is responsible for deleting the file and freeing the path.
Thread-safe.

Definition at line 844 of file filepath.c.

References filepath_join(), and get_tempdir().

Here is the call graph for this function:

◆ path_exists()

bool path_exists ( const char *  path)

Checks if a path exists in the filesystem.

Parameters
pathPath to check. Must not be NULL.
Returns
true if path exists (file, directory, or other), false otherwise.
Note
Follows symbolic links.
Thread-safe.

Definition at line 926 of file filepath.c.

◆ user_home_dir()

const char * user_home_dir ( void  )

Returns the user's home directory path.

Returns
Pointer to home directory string, or NULL if not found.
Note
On Windows, returns USERPROFILE environment variable.
On POSIX, returns HOME environment variable.
The returned pointer must NOT be freed (points to environment).
Thread-safe if environment is not being modified.

Definition at line 1070 of file filepath.c.

References GETENV.

Referenced by filepath_expanduser(), and filepath_expanduser_buf().

Here is the caller graph for this function: