Frans
Frans

Reputation: 89

C function - cd representation not working

void cd(char *path) {
    int ret;
    if (strlen (path) > 0) {
        if (path[strlen (path) - 1] == '\n') {
            path[strlen (path) - 1] = '\0';
        }
    }
    ret = chdir(path);
    if(ret == -1) {
        perror("changing directory failed:");
    }
}

This is my cd function that is supposed to represent a simple version of the cd function in linux, it works if I want to go into a directory but if I want to go back it does not work to use "cd -", anyone that knows how to fix this?

Upvotes: 1

Views: 82

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140196

- is not supported by the C library chdir, but only by the shell cd command.

To be able to use this feature in a C program, you have to emulate it. For instance by storing the current path before performing a chdir:

void cd(char *path) {
    int ret;
    // used to store the previous path
    static char old_path[MAX_PATH_LEN] = "";

    if (strlen (path) > 0) {
        if (path[strlen (path) - 1] == '\n') {
            path[strlen (path) - 1] = '\0';
        }
    }
    if (!strcmp(path,"-"))
    {
        // - special argument: use previous path
        if (old_path[0]=='\0')
        {
           // no previous path: error
           return -1;
        }
        path = old_path;  // use previous path
    }
    else
    {   
        // memorize current path prior to changing
        strcpy(old_path,getcwd());
    }
    ret = chdir(path);
    if(ret == -1) {
        perror("changing directory failed:");
    }
}

It may be need tuning in case the user uses - twice, maybe a stack of paths could be used, but the principle is there.

Upvotes: 2

Related Questions