1

I am trying to develop a shell in C/POSIX on my Mac OS X. For the cd command, I can successfully change the directory of the shell with the chdir method in most cases except when the path has spaces in it. For example, a path such as

/users/bayesianStudent/desktop

correctly changes the directory but the following,

/users/bayesianStudent/desktop/Spring\ 2016

return error message:

No such file or directory

However, if I take the same path and use the regular terminal, it works normally(so nothing is wrong with the path). Following is a dummy program that replicates the issue:

#include    <stdio.h>
#include    <stdlib.h>

int main()
{
    char path[1024];
    char cwd[1024];

    printf("Please enter path:\n");
    gets(path);
    printf("Trying to change the path to %s\n", path );

    int i = chdir(path);
    if( i == 0 )
    {
        printf("sucess\n");
        if (getcwd(cwd, sizeof(cwd)) != NULL)
            fprintf(stdout, "Current working dir: %s\n", cwd);
        else
            perror("getcwd() error");
    }
    else
    {
        perror("Directory not changed: ");
    }
    return 0;
}

Also, since I am developing a shell, I run into same problem with other commands that use file path such as ls. For instance, I get a similar message for(when there are spaces but path is correct):

execvp("ls", path, NULL);
Jenna Maiz
  • 792
  • 4
  • 17
  • 38

1 Answers1

2

As you are not very specific which path you enter into your program, I try to explain what happens:

  1. If you issue a shell command like cd, the shell interprets the command line and splits it at unescaped whitespace. In your example, you don't want it to split your path name between Spring and 2016, so you escape that space.

    In other words, the shell turns your /users/bayesianStudent/desktop/Spring\ 2016 into /users/bayesianStudent/desktop/Spring 2016 and that's what arrives at the program.

  2. If you input a path into a program as in

    printf("Please enter path:\n");
    gets(path);
    

    you don't have escaping so you have to enter the path as it is. Especially, if you enter /users/bayesianStudent/desktop/Spring\ 2016, your program will see the string including the \ and sees that no such directory exists.

glglgl
  • 89,107
  • 13
  • 149
  • 217