getcwd()

Updated: April 19, 2023

Get the name of the current working directory

Synopsis:

#include <unistd.h>

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

Arguments:

buffer
NULL, or a pointer to a buffer where the function can store the directory name.
size
The size of the buffer, in bytes.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The getcwd() function returns the name of the current working directory. buffer is a pointer to a buffer of at least size bytes where the NUL-terminated name of the current working directory will be placed.

The maximum size that might be required for buffer is PATH_MAX bytes. See <limits.h>.

Note: POSIX doesn't specify what should happen if you call getcwd( NULL, 0). The QNX Neutrino version (like many others) allocates a buffer for the name of the directory; it's up to your application to free the buffer when you no longer need it.

Returns:

The address of the string containing the name of the current working directory, or NULL if an error occurred (errno is set).

Errors:

EINVAL
The argument size is negative or 0.
ELOOP
Too many levels of symbolic links.
ENOSYS
The getcwd() function isn't implemented for the filesystem specified in the current working directory.
ERANGE
The buffer is too small (as specified by size) to contain the name of the current working directory.

Examples:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <limits.h>

int main( void )
{
    char* cwd;
    char buff[PATH_MAX];

    cwd = getcwd( buff, PATH_MAX );
    if( cwd != NULL ) {
        printf( "My working directory is %s.\n", cwd );
    }

    return EXIT_SUCCESS;
}

produces the output:

My working directory is /home/bill.

Classification:

POSIX 1003.1

Safety:  
Cancellation point Yes
Interrupt handler No
Signal handler No
Thread Yes

Caveats:

There is only one current working directory per process. In a multithreaded application, any thread calling chdir() will change the current working directory for all threads in that process.