1GETCWD(P)                  POSIX Programmer's Manual                 GETCWD(P)
2
3
4

NAME

6       getcwd - get the pathname of the current working directory
7

SYNOPSIS

9       #include <unistd.h>
10
11       char *getcwd(char *buf, size_t size);
12
13

DESCRIPTION

15       The  getcwd()  function shall place an absolute pathname of the current
16       working directory in the array pointed to by buf, and return  buf.  The
17       pathname  copied to the array shall contain no components that are sym‐
18       bolic links. The size argument is the size in bytes  of  the  character
19       array  pointed  to  by  the buf argument. If buf is a null pointer, the
20       behavior of getcwd() is unspecified.
21

RETURN VALUE

23       Upon successful completion, getcwd() shall  return  the  buf  argument.
24       Otherwise,  getcwd() shall return a null pointer and set errno to indi‐
25       cate the error. The contents of the array pointed to by  buf  are  then
26       undefined.
27

ERRORS

29       The getcwd() function shall fail if:
30
31       EINVAL The size argument is 0.
32
33       ERANGE The  size  argument  is  greater than 0, but is smaller than the
34              length of the pathname +1.
35
36
37       The getcwd() function may fail if:
38
39       EACCES Read or search permission was denied  for  a  component  of  the
40              pathname.
41
42       ENOMEM Insufficient storage space is available.
43
44
45       The following sections are informative.
46

EXAMPLES

48   Determining the Absolute Pathname of the Current Working Directory
49       The  following  example  returns  a  pointer to an array that holds the
50       absolute pathname of the current  working  directory.  The  pointer  is
51       returned  in  the ptr variable, which points to the buf array where the
52       pathname is stored.
53
54
55              #include <stdlib.h>
56              #include <unistd.h>
57              ...
58              long size;
59              char *buf;
60              char *ptr;
61
62
63              size = pathconf(".", _PC_PATH_MAX);
64
65
66              if ((buf = (char *)malloc((size_t)size)) != NULL)
67                  ptr = getcwd(buf, (size_t)size);
68              ...
69

APPLICATION USAGE

71       None.
72

RATIONALE

74       Since the maximum pathname length is  arbitrary  unless  {PATH_MAX}  is
75       defined,  an  application  generally  cannot  supply  a  buf  with size
76       {{PATH_MAX}+1}.
77
78       Having getcwd() take no arguments and instead use the malloc() function
79       to  produce  space for the returned argument was considered. The advan‐
80       tage is that getcwd() knows how big the working directory  pathname  is
81       and  can  allocate  an  appropriate amount of space. But the programmer
82       would have to use the free() function to free the resulting object,  or
83       each  use  of getcwd() would further reduce the available memory. Also,