pathfind(), pathfind_r()

Updated: April 19, 2023

Search for a file in a list of directories

Synopsis:

#include <libgen.h>

char *pathfind( const char *path,
                const char *name,
                const char *mode );

char *pathfind_r( const char *path,
                  const char *name,
                  const char *mode,
                  char *buff,
                  size_t buff_size );

Arguments:

path
A string that specifies the list of the directories that you want to search. The directories named in path are separated by colons.
name
The name of the file you're looking for. If name begins with a slash, the name is treated as an absolute pathname, and path is ignored.
mode
A string of option letters chosen from:
r
Readable.
w
Writable.
x
Executable.
f
Normal file.
b
Block special.
c
Character special.
d
Directory.
p
FIFO (pipe).
u
Set user ID bit.
g
Set group ID bit.
k
Sticky bit.
s
Size nonzero.
buff
(pathfind_r() only) A pointer to a buffer where pathfind_r() can store the path of the file found.
buff_size
(pathfind_r() only) The size of the buffer that buff points to.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The pathfind() function searches the directories named in path for the file name. The pathfind_r() function is a thread-safe version of pathfind().

Options read, write, and execute are checked relative to the real (not the effective) user ID and group ID of the current process.

If the file name, with all the characteristics specified by mode, is found in any of the directories specified by path, then these functions return a pointer to a string containing the member of path, followed by a slash character (/), followed by name.

An empty path member is treated as the current directory. If name is found in the current directory, a slash isn't prepended to it; the unadorned name is returned.

The pathfind_r() also includes a buffer, buff, and its size, buff_size. This buffer is used to hold the path of the file found.

Returns:

The path found, or NULL if the file couldn't be found.

Examples:

Find the ls command using the PATH environment variable:

pathfind (getenv ("PATH"), "ls", "rx");

Classification:

Unix

Table 1. pathfind()
Safety:  
Cancellation point Yes
Interrupt handler No
Signal handler No
Thread No
Table 2. pathfind_r()
Safety:  
Cancellation point Yes
Interrupt handler No
Signal handler Yes
Thread Yes

Caveats:

The string pointed to by the returned pointer is stored in an area that's reused on subsequent calls to pathfind(). Don't free this string.

Use pathfind_r() in multithreaded applications.