Each process has associated with it a directory, called its current working directory or simply working directory, that is used in the resolution of relative file names (see File Name Resolution).
When you log in and begin a new session, your working directory is initially set to the home directory associated with your login account in the system user database. You can find any user's home directory using the getpwuid
or getpwnam
functions; see User Database.
Users can change the working directory using shell commands like cd
. The functions described in this section are the primitives used by those commands and by other programs for examining and changing the working directory.
Prototypes for these functions are declared in the header file `unistd.h'.
getcwd
function returns an absolute file name representing the current working directory, storing it in the character array buffer that you provide. The size argument is how you tell the system the allocation size of buffer.
The GNU library version of this function also permits you to specify a null pointer for the buffer argument. Then getcwd
allocates a buffer automatically, as with malloc
(see Unconstrained Allocation). If the size is greater than zero, then the buffer is that large; otherwise, the buffer is as large as necessary to hold the result.
The return value is buffer on success and a null pointer on failure. The following errno
error conditions are defined for this function:
EINVAL
ERANGE
EACCES
Here is an example showing how you could implement the behavior of GNU's getcwd (NULL, 0)
using only the standard behavior of getcwd
:
char * gnu_getcwd () { int size = 100; char *buffer = (char *) xmalloc (size); while (1) { char *value = getcwd (buffer, size); if (value != 0) return buffer; size *= 2; free (buffer); buffer = (char *) xmalloc (size); } }
See Malloc Examples, for information about xmalloc
, which is not a library function but is a customary name used in most GNU software.
getcwd
, but has no way to specify the size of the buffer. The GNU library provides getwd
only for backwards compatibility with BSD.
The buffer argument should be a pointer to an array at least PATH_MAX
bytes long (see Limits for Files). In the GNU system there is no limit to the size of a file name, so this is not necessarily enough space to contain the directory name. That is why this function is deprecated.
The normal, successful return value from chdir
is 0
. A value of -1
is returned to indicate an error. The errno
error conditions defined for this function are the usual file name syntax errors (see File Name Errors), plus ENOTDIR
if the file filename is not a directory.