Arman Iqbal
Arman Iqbal

Reputation: 755

My chdir() function will not work. Why?

I am writing a program that asks the user for a linux bash command and then stores them in pointer arrays (kind of like char *argv[]). The program must then make a check if this command is a normal bash command or a cd (change directory) command. If its a cd command then it should use something like chdir(). If the command is anything else I wanna use some variation of the exec() system call to execute that command.

However I am not succeeding with the first part (chdir()).

int ii=-1
printf("Enter the command: ");
fgets(command, 100, stdin);
command[strlen(command)-1]=0;
printf("Command = %s\n", command);


if (command[0]=='c' && command[1]=='d' && command[2]==' ')
{
    printf("I am inside CD now.\n");
    cd_dump[0] = strtok(command," ");
    while(sub_string[++ii]=strtok(NULL, " ") != NULL)
    {
        printf("%s\n", sub_string[0]);
    }

    chdir(sub_string[0]);
}

Edit: I have also tried the following if statement without luck.

if (command[0]=='c' && command[1]=='d' && command[2]==' ')
{
    printf("I am inside CD now.\n");
    chdir(command+3);
}

Sadly the program isn´t doing what I want it to, and even after hours trying to solve the issue I have no idea why. What have I done wrong? Also if I input cd /home/ why does the output result in sub_string[0] end up with an extra "Enter key" on the output? Does strtok save the Enter key into the string?

Any help on the subject is very much appreciated.

Upvotes: 0

Views: 1593

Answers (2)

glglgl
glglgl

Reputation: 91059

Calling chdir() only affects the current process, not its parent process.

If you chdir() and exit immediately, it is pointless - the shell you call it from keeps its old cwd. That's why cd is always a shell builtin.

Use

char buffer[PATH_MAX];
if (getcwd(buffer, sizeof buffer) >= 0) {
    printf("Old wd: %s\n", buffer);
}
chdir(command+3);
if (getcwd(buffer, sizeof buffer) >= 0) {
    printf("New wd: %s\n", buffer);
}

to verify chdir() works correctly.

Upvotes: 2

user2624417
user2624417

Reputation: 67

I think I'd do something like this:

if (command[0]=='c' && command[1]=='d' && command[2]==' ')
{
    for(i=2, i++, command[i]!=' ');  /* Skip to nonspace */
    chdir(command+i);
}

Upvotes: 0

Related Questions