4

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.

Razib
  • 10,965
  • 11
  • 53
  • 80
user4493605
  • 391
  • 2
  • 18

2 Answers2

4

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.

Razib
  • 10,965
  • 11
  • 53
  • 80
1

You will need to store the CWD in a string first:

char *cwd;
cwd = getcwd(NULL, 0);
if(cwd == NULL) { 
    // error
    return -1;
}
if(strcmp("/whatever", cwd) == 0) {
    // same folder
}
free(cwd);
mrks
  • 8,033
  • 1
  • 33
  • 62
  • 1
    That code will lead to *undefined behavior*. The implementations that allocate the string for you needs you to pass in `NULL` for the *first* argument. Also note that not all implementations will allocate memory, it's not standardized. – Some programmer dude Mar 07 '15 at 07:15