#include <unistd.h>
|
char *
getcwd (char *buf, size_t size); |
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.
#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:
[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. | |
© 2005-2007 Nokia |