Name

getcwd - gets current working directory

Library

libc.lib

Synopsis

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

Return values

Upon successful completion, a pointer to the pathname is returned. Otherwise a NULL pointer is returned and the global variable errno is set to indicate the error. In addition, getwd copies the error message associated with errno into the memory referenced by buf.

Detailed description

The getcwd function copies the absolute pathname of the current working directory into the memory referenced by buf and returns a pointer to buf. The size argument is the size, in bytes, of the array referenced by buf.

If buf is NULL, space is allocated as indicated by size to store the pathname and the current working directory is returned as long as the size bytes are sufficient to hold the working directory name. This space may later be free’d.

This routine has traditionally been used by programs to save the name of a working directory for the purpose of returning to it. A much faster and less error-prone method of accomplishing this is to open the current directory (‘.’) and use the fchdir function to return.


Examples

#include<unistd.h>
#include<stdio.h>
#include <stdlib.h>
#define BUF_SIZE 100
  
int main()
{
 //change directory to c:
 int c;
 long size = BUF_SIZE;
 char *buf = NULL;
 char *ptr = NULL;
  
 c = chdir("c:\\");
  
 buf = (char *)malloc((size_t)size);
  
 if (buf != NULL && c == 0)
 {
  //call getcwd to fetch teh current directory
  ptr = getcwd(buf, (size_t)size);
  printf("getcwd returned: %s\n", ptr);
 }
   
 return 0;
}

         

Output

getcwd returned: c:

         

Errors

The getcwd function will fail if:
[EACCES]
  Read or search permission was denied for a component of the pathname.
[EINVAL]
  The size argument is zero and buf is not a null pointer.
[ENOENT]
  A component of the pathname no longer exists.
[ENOMEM]
  Insufficient memory is available.
[ERANGE]
  The size argument is less than the length of the working directory name. Allocate a bigger array and try again.

Notes

The getcwd function returns the default working directory as c: \private \XXXXXXXX (where XXXXXXXX is the UID of the process) as the default session path is initialised to c: \private\current_process’_UID, in case of symbian.

See also

chdir, malloc, strerror

Feedback

For additional information or queries on this page send feedback

© 2005-2007 Nokia

Top