GETCWD(3C) Standard C Library Functions GETCWD(3C)
NAME
getcwd - get pathname of current working directory
SYNOPSIS
#include <unistd.h> char * getcwd(
char *buf,
size_t size);
DESCRIPTION
The
getcwd() function returns a pointer to a buffer containing the absolute
pathname of the current working directory. The returned pathname contains
no components that are symbolic links.
When
buf is not NULL, the absolute pathname will be written into
buf and
size represents the length in bytes of
buf. If the length of the pathname
and nul terminator exceeds
size, nothing will be written and
getcwd() will
return NULL. Otherwise,
getcwd() returns
buf.
When
buf is NULL then
getcwd() will allocate memory in which to store the
pathname of the current working directory. If
size is non-zero, then
size bytes will be allocated. If the length of the pathname and nul terminator
exceeds
size, the memory will be freed and
getcwd() will return NULL. If
size is zero, then
getcwd() will attempt to allocate enough space to hold
the pathname. In both cases, it is the caller's responsibility to free the
returned buffer with the
free(3C) function.
RETURN VALUES
Upon successful completion, the
getcwd() function returns a pointer to a
buffer containing the pathname. Otherwise, NULL is returned and
errno is
set to indicate the error.
EXAMPLES
Example 1 Determine the absolute pathname of the current working directory.
The following example returns a pointer to an array that holds the absolute
pathname of the current working directory. The pointer is returned in the
ptr variable, which points to the
buf array where the pathname is stored.
#include <stdlib.h>
#include <unistd.h>
...
long size;
char *buf;
char *ptr;
size = pathconf(".", _PC_PATH_MAX);
if ((buf = (char *)malloc((size_t)size)) != NULL)
ptr = getcwd(buf, (size_t)size);
...
Example 2 Print the current working directory.
The following example prints the current working directory.
#include <stdio.h>
#include <unistd.h>
int
main(void)
{
char *cwd;
if ((cwd = getcwd(NULL, 0)) == NULL) {
perror("pwd");
exit(2);
}
(void)printf("%s\n", cwd);
free(cwd); /* free memory allocated by getcwd() */
return(0);
}
ERRORS
The
getcwd() function will fail if:
EFAULT The
buf argument points to an invalid address.
EINVAL The
buf argument is not NULL and the
size argument is 0.
ERANGE The pathname (including its terminating nul character)
is too long to fit into the provided (or allocated)
buffer.
EACCESS A parent directory cannot be read to get its name.
ENOMEM Insufficient storage space is available.
USAGE
Applications should exercise care when using
chdir(2) in conjunction with
getcwd(). The current working directory is global to all threads within a
process. If more than one thread calls
chdir(2) to change the working
directory, a subsequent call to
getcwd() could produce unexpected results.
INTERFACE STABILITY
CommittedSEE ALSO
chdir(2),
free(3C),
attributes(7),
standards(7)OmniOS February 27, 2021 OmniOS