getcwd() — Get path name of the working directory

Standards

Standards / Extensions C or C++ Dependencies
POSIX.1
XPG4
XPG4.2
Single UNIX Specification, Version 3
both  

Format

#define _POSIX_SOURCE
#include <unistd.h>

char *getcwd(char *buffer, size_t size);

General description

Determines the path name of the working directory and stores it in buffer.
size
The number of characters in the buffer area.
buffer
The name of the buffer that will be used to hold the path name of the working directory. buffer must be big enough to hold the working directory name, plus a terminating NULL to mark the end of the name.

Returned value

If successful, getcwd() returns a pointer to the buffer.

If unsuccessful, getcwd() returns a NULL pointer and sets errno to one of the following values:
Error Code
Description
EACCES
The process did not have read or search permission on some component of the working directory's path name.
EINVAL
size is less than or equal to zero.
EIO
An input/output error occurred.
ENOENT
A component of the working directory's path name does not exist.
ENOTDIR
A directory component of the working directory's path name is not really a directory.
ERANGE
size is greater than 0, but less than the length of the working directory's path name, plus 1 for the terminating NULL.

Example

CELEBG03
/* CELEBG03

   This example determines the working directory.

 */
#define _POSIX_SOURCE
#include <unistd.h>
#undef _POSIX_SOURCE
#include <stdio.h>

main() {
  char cwd[256];

  if (chdir("/tmp") != 0)
    perror("chdir() error()");
  else {
    if (getcwd(cwd, sizeof(cwd)) == NULL)
      perror("getcwd() error");
    else
      printf("current working directory is: %s\n", cwd);
  }
}
Output
current working directory is: /tmp

Related information