gtpc2m3nC/C++ Language Support User's Guide

getcwd-Get Path Name of the Working Directory

This function gets path name of the working directory.

Format

#include <unistd.h>
char *getcwd(char *buffer, size_t size);

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.

This function determines the path name of the working directory and stores it in buffer.

Normal Return

If successful, the getcwd function returns a pointer to the buffer.

Error Return

If unsuccessful, the getcwd function returns a NULL pointer.

If getcwd function fails, it sets errno to one of the following:

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.

ERANGE
size is greater than zero, but less than the length of the working directory's path name, plus 1 for the terminating NULL.

Programming Considerations

If buffer is a NULL pointer, the getcwd function allocates size bytes and returns the address of the allocated buffer. The caller should free the buffer (using the free function) when it is no longer needed. This behavior is provided for Berkeley Software Distribution (BSD) compatibility, but this use of the getcwd function is not recommended because the preferred usage is for the user to manage the buffer where output is returned.

Examples

The following example determines the working directory.

#include <unistd.h>
#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

chdir-Change the Working Directory.

See Appendix E, Programming Support for the TPF File System for more information about TPF File System C Functions.