1GETCWD(3P) POSIX Programmer's Manual GETCWD(3P)
2
3
4
6 This manual page is part of the POSIX Programmer's Manual. The Linux
7 implementation of this interface may differ (consult the corresponding
8 Linux manual page for details of Linux behavior), or the interface may
9 not be implemented on Linux.
10
12 getcwd — get the pathname of the current working directory
13
15 #include <unistd.h>
16
17 char *getcwd(char *buf, size_t size);
18
20 The getcwd() function shall place an absolute pathname of the current
21 working directory in the array pointed to by buf, and return buf. The
22 pathname shall contain no components that are dot or dot-dot, or are
23 symbolic links.
24
25 If there are multiple pathnames that getcwd() could place in the array
26 pointed to by buf, one beginning with a single <slash> character and
27 one or more beginning with two <slash> characters, then getcwd() shall
28 place the pathname beginning with a single <slash> character in the
29 array. The pathname shall not contain any unnecessary <slash> charac‐
30 ters after the leading one or two <slash> characters.
31
32 The size argument is the size in bytes of the character array pointed
33 to by the buf argument. If buf is a null pointer, the behavior of
34 getcwd() is unspecified.
35
37 Upon successful completion, getcwd() shall return the buf argument.
38 Otherwise, getcwd() shall return a null pointer and set errno to indi‐
39 cate the error. The contents of the array pointed to by buf are then
40 undefined.
41
43 The getcwd() function shall fail if:
44
45 EINVAL The size argument is 0.
46
47 ERANGE The size argument is greater than 0, but is smaller than the
48 length of the string +1.
49
50 The getcwd() function may fail if:
51
52 EACCES Search permission was denied for the current directory, or read
53 or search permission was denied for a directory above the cur‐
54 rent directory in the file hierarchy.
55
56 ENOMEM Insufficient storage space is available.
57
58 The following sections are informative.
59
61 The following example uses {PATH_MAX} as the initial buffer size
62 (unless it is indeterminate or very large), and calls getcwd() with
63 progressively larger buffers until it does not give an [ERANGE] error.
64
65
66 #include <stdlib.h>
67 #include <errno.h>
68 #include <unistd.h>
69
70 ...
71
72 long path_max;
73 size_t size;
74 char *buf;
75 char *ptr;
76
77 path_max = pathconf(".", _PC_PATH_MAX);
78 if (path_max == -1)
79 size = 1024;
80 else if (path_max > 10240)
81 size = 10240;
82 else
83 size = path_max;
84
85 for (buf = ptr = NUL