GETCWD(3C) | Standard C Library Functions | GETCWD(3C) |
getcwd
—
#include <unistd.h>
char *
getcwd
(char *buf,
size_t size);
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.
getcwd
() function
returns a pointer to a buffer containing the pathname. Otherwise,
NULL
is returned and errno is
set to indicate the error.
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); }
getcwd
() function will fail if:
EFAULT
EINVAL
NULL
and the size argument is 0.ERANGE
EACCESS
ENOMEM
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.
February 27, 2021 | OmniOS |