-1

building a small shell like prog

i try to make cd command, so i use:

if (!strcmp(cmd, "cd") ) 
    {
        if(chdir("args[1]")!=0){
            printf(" %s - path not found\n",args[1]);
            perror("Error:");
        }
    } 

the output is this:

smash > cd /home/johnny/workspace/
 /home/johnny/workspace/ - path not found
Error:: No such file or directory
smash > cd test
 test - path not found
Error:: No such file or directory

ps there is a "test" folder in the working dir

pps maybe you guys can help me on how to make "cd .." command

JohnnyF
  • 1,053
  • 4
  • 16
  • 31
  • 6
    `chdir("args[1]")` - are you sure you have a directory named `args[1]`? Because in C string literals won't be parsed to account for variables and such, this isn't PHP. What you want to do is (probably) `chdir(args[1])` (note the lack of double quotes). – user4520 Nov 15 '15 at 16:07
  • Study the source code of existing shells for inspiration – Basile Starynkevitch Nov 15 '15 at 16:20
  • in general, a call to `perror()` needs to be immediately after the call to the system function that set errno. The posted code, after corrections for the parameter to `chdir()`, contains an intervening call to `printf()`, which, on error, would have changed the value in `errno`. Suggest placing the call to `perror()` immediately after the call to `chdir()` – user3629249 Nov 15 '15 at 17:02

1 Answers1

7

You are passing the actual string "args[1]" into chdir. This probably is not what you want bu instead you want chdir(args[1]) So your code would look like this:

if (!strcmp(cmd, "cd") ) 
    {
        if(chdir(args[1])!=0){
            fprintf(stderr, "chdir %s failed: %s\n", args[1], strerror(errno));
        }
    } 

From the output of printf your path seems ok, notice that in printf you dont have "args[1]" but instead you have args[1].

Also as pointed by @BasileStarynkevitch in the comment bellow:

perror after a printf is wrong (since a failed printf would change errno).

And therefore you should use the fprintf above.

PeCosta
  • 537
  • 4
  • 13
  • 1
    `perror` after a `printf` is wrong (since a failed `printf` would change `errno`). Replace both `printf` & `perror` calls with simply: `fprintf(stderr, "chdir %s failed: %s\n", args[1], strerror(errno));` – Basile Starynkevitch Nov 15 '15 at 16:19