Search code examples
ciodirectorygetcwd

C programming getcwd variable manipulation


Basically I need an if statement of which the response is dependent upon the current working directory.

I have done some research on the topic and I believe that the getcwd() function is what I am looking for, but I can't figure out how to interface with it in an if statement.

I am new to C, and the program I am making needs to be located on the Desktop (btw its a UNIX system) for it to run properly and the if statement needs to determine whether it is located on said desktop or not.


Solution

  • What about the following code it's work for me on ubuntu -

    #include <stdlib.h>
    #include <unistd.h>
    #include <limits.h>
    
    int main( void ){
    
        char* cwd;
        char buff[PATH_MAX + 1];
    
        cwd = getcwd( buff, PATH_MAX + 1 );
        if( cwd != NULL ) {
            printf( "My working directory is %s.\n", cwd );
    
            if(strcmp("/home/razib/Desktop", cwd) == 0) {
                printf("I'm in Desktop now\n");
            }
        }
    
        return EXIT_SUCCESS;
    }   
    

    Here you have to provide getcwd() method a buff[]. The buff[] may be declared with size PATH_MAX+1. PATH_MAX can be found at limits.h.

    Hope it will help you.
    Thanks a lot.