GETCWD(3P)
π GETCWD(3P) β the POSIX Programmer's Manual, bestie edition π
okay so before we even get into it β PROLOG time, because there's lore β¨
This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. π«Ά
πΈ NAME πΈ
getcwd β get the pathname of the current working directory
like. it tells you where you are. your location. your address in the filesystem. iconic behaviour honestly π
β¨ SYNOPSIS β¨
#include <unistd.h>
char *getcwd(char *buf, size_t size);
π¦ DESCRIPTION π¦
So the getcwd() function shall place an absolute pathname of the current working directory in the array pointed to by buf, and return buf. No cap, that's the whole job. π
And the pathname shall contain no components that are dot or dot-dot, or are symbolic links. So no .. shenanigans, no symlink trickery. Clean pathname only, we don't do that here β
Now if there are multiple pathnames that getcwd() could place in the array pointed to by buf, one beginning with a single <slash> character and one or more beginning with two <slash> characters, then getcwd() shall place the pathname beginning with a single <slash> character in the array. The pathname shall not contain any unnecessary <slash> characters after the leading one or two <slash> characters. like it's not gonna be out here going //usr///bin okay?? it has standards β¨
The size argument is the size in bytes of the character array pointed to by the buf argument.
β οΈ Ifbufis a null pointer, the behavior ofgetcwd()is unspecified. that's the "we literally cannot tell you what happens" zone. don't. π
π RETURN VALUE π
Upon successful completion, getcwd() shall return the buf argument. π (yes it just hands you back your own buffer, it's giving generous queen energy)
Otherwise, getcwd() shall return a null pointer and set errno to indicate the error. The contents of the array pointed to by buf are then undefined. so like. don't trust that buffer after a fail, bestie, it's in its flop era π
π₯ ERRORS π₯
The getcwd() function shall fail if:
EINVALβ Thesizeargument is0. bestie you gave it zero bytes. what did you expect. πERANGEβ Thesizeargument is greater than0, but is smaller than the length of the string+1. the buffer is too smol, the path is too big, it's giving mismatch π
The getcwd() function may fail if:
EACCESβ Search permission was denied for the current directory, or read or search permission was denied for a directory above the current directory in the file hierarchy. π«ENOMEMβ Insufficient storage space is available. no room, no path, no vibe π«
The following sections are informative. (translation: the drama is over, now we're just chatting π )
π§ EXAMPLES π§
okay this one's so good. The following example uses {PATH_MAX} as the initial buffer size (unless it is indeterminate or very large), and calls getcwd() with progressively larger buffers until it does not give an [ERANGE] error. it's the grow-until-it-fits method, we love a persistent queen π
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
...
long path_max;
size_t size;
char *buf;
char *ptr;
path_max = pathconf(".", _PC_PATH_MAX);
if (path_max == -1)
size = 1024;
else if (path_max > 10240)
size = 10240;
else
size = path_max;
for (buf = ptr = NULL; ptr == NULL; size *= 2)
{
if ((buf = realloc(buf, size)) == NULL)
{
... handle error ...
}
ptr = getcwd(buf, size);
if (ptr == NULL && errno != ERANGE)
{
... handle error ...
}
}
...
free (buf);
π APPLICATION USAGE π
So here's the tea. If the pathname obtained from getcwd() is longer than {PATH_MAX} bytes, it could produce an [ENAMETOOLONG] error if passed to chdir(). π
Therefore, in order to return to that directory it may be necessary to break the pathname into sections shorter than {PATH_MAX} bytes and call chdir() on each section in turn (the first section being an absolute pathname and subsequent sections being relative pathnames). like chopping your journey into little bites so nothing chokes π
A simpler way to handle saving and restoring the working directory when it may be deeper than {PATH_MAX} bytes in the file hierarchy is to use a file descriptor and fchdir(), rather than getcwd() and chdir(). slay, less work β¨
But β and this is important, no skipping β the two methods do have some differences:
- The
fchdir()approach causes the program to restore a working directory even if it has been renamed in the meantime, whereas thechdir()approach restores to a directory with the same name as the original, even if the directories were renamed in the meantime. π·οΈ - Since the
fchdir()approach does not access parent directories, it can succeed whengetcwd()would fail due to permissions problems. π - In applications conforming to earlier versions of this standard, it was not possible to use the
fchdir()approach when the working directory is searchable but not readable, as the only way to open a directory was withO_RDONLY, whereas thegetcwd()approach can succeed in this case. π°οΈ
π RATIONALE π
the behind-the-scenes commentary, we're in the writer's room now π¬
Having getcwd() take no arguments and instead use the malloc() function to produce space for the returned argument was considered. The advantage is that getcwd() knows how big the working directory pathname is and can allocate an appropriate amount of space. But the programmer would have to use the free() function to free the resulting object, or each use of getcwd() would further reduce the available memory. leak era, we don't want it π«
Finally, getcwd() is taken from the SVID where it has the two arguments used in this volume of POSIX.1β2017. π
The older function getwd() was rejected for use in this context because it had only a buffer argument and no size argument, and thus had no way to prevent overwriting the buffer, except to depend on the programmer to provide a large enough buffer. yikes, imagine π
On some implementations, if buf is a null pointer, getcwd() may obtain size bytes of memory using malloc(). In this case, the pointer returned by getcwd() may be used as the argument in a subsequent call to free().
β οΈ Invokinggetcwd()withbufas a null pointer is not recommended in conforming applications. we said what we said π
Earlier implementations of getcwd() sometimes generated pathnames like "../../../subdirname" internally, using them to explore the path of ancestor directories back to the root. If one of these internal pathnames exceeded {PATH_MAX} in length, the implementation could fail with errno set to [ENAMETOOLONG]. This is no longer allowed. glow-up achieved β¨
If a program is operating in a directory where some (grand)parent directory does not permit reading, getcwd() may fail, as in most implementations it must read the directory to determine the name of the file. This can occur if search, but not read, permission is granted in an intermediate directory, or if the program is placed in that directory by some more privileged process (for example, login). π
Including the [EACCES] error condition makes the reporting of the error consistent and warns the application developer that getcwd() can fail for reasons beyond the control of the application developer or user. Some implementations can avoid this occurrence (for example, by implementing getcwd() using pwd, where pwd is a set-user-root process), thus the error was made optional.
Since this volume of POSIX.1β2017 permits the addition of other errors, this would be a common addition and yet one that applications could not be expected to deal with without this addition. (yes, that sentence is a whole journey. we read it. we survived. π
)
β FUTURE DIRECTIONS β
None.
like, nothing. zero. the future is now, bestie, nothing's changing π
π SEE ALSO π
malloc()- The Base Definitions volume of
POSIX.1β2017,<unistd.h>
π COPYRIGHT π
okay legal moment, stay with me, it's important π«Ά
Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .
and that's the whole page, bestie!! πβ¨ this one came from IEEE/The Open Group, dated 2017, and it's the GETCWD(3P) page β go forth and always know where you are π¦πΈπ
π¦ where this page comes from
- alpine 3.22: man-pages-posix 2017a-r0 Β· custom
- alpine 3.23: man-pages-posix 2017a-r0 Β· custom
- alpine 3.24: man-pages-posix 2017a-r0 Β· custom
- arch rolling: man-pages 6.19-1
- arch rolling: man-pages 6.20-1 Β· BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
- nixpkgs unstable: man-pages-posix 2017a
- opensuse-leap 16.0: man-pages-posix 2017a-160000.4.1 Β· SUSE-IEEE
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms