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.

4

2 回答 2

4

下面的代码对我有用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;
}   

在这里你必须提供getcwd()方法 a buff[]buff[]可以用 size声明PATH_MAX+1PATH_MAX可以在limits.h.

希望它会帮助你。
非常感谢。

于 2015-03-07T08:02:35.420 回答
1

您需要先将 CWD 存储在字符串中:

char *cwd;
cwd = getcwd(NULL, 0);
if(cwd == NULL) { 
    // error
    return -1;
}
if(strcmp("/whatever", cwd) == 0) {
    // same folder
}
free(cwd);
于 2015-03-07T07:11:45.710 回答