Find the answer to your Linux question:
Results 1 to 6 of 6
What is the reason for the "cd" command not working through "system".. In example system("cd") does not execute. Or maybe there is a trick to making it work.... THaNx...
  1. #1
    Just Joined!
    Join Date
    Sep 2007
    Posts
    3

    why System("cd") doesn't work?

    What is the reason for the "cd" command not working through "system".. In example system("cd") does not execute. Or maybe there is a trick to making it work....

    THaNx

  2. #2
    Linux Enthusiast likwid's Avatar
    Join Date
    Dec 2006
    Location
    MA
    Posts
    649
    What makes you think it doesn't execute? You might want to try the full path.

  3. #3
    Linux Enthusiast likwid's Avatar
    Join Date
    Dec 2006
    Location
    MA
    Posts
    649
    I don't think full path actually makes any difference, should work. Example:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
            system("ls");
            return(0);
    }
    That works fine.

  4. #4
    Linux Enthusiast
    Join Date
    Aug 2006
    Posts
    631
    A system command runs in a sub-shell, so a "cd" in your program changes the working directory of the sub-shell, not its parent, the shell from which the sub-shell was launched.
    When the command exits, you're back in the original directory because the current shell has not done a "cd".

    Use the chdir() function.

    Regards

  5. #5
    Just Joined!
    Join Date
    Sep 2007
    Posts
    10

    Smile

    Quote Originally Posted by static_cast View Post
    What is the reason for the "cd" command not working through "system".. In example system("cd") does not execute. Or maybe there is a trick to making it work....

    THaNx
    Hello , well maybe u need use cd whit parameters for example:

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

    int main()
    {
    system("cd --"); // go to root
    //or
    system("cd /home/user"); // go to folder "your name user"

    return 0;
    }

    good luck1.

  6. #6
    Linux Enthusiast likwid's Avatar
    Join Date
    Dec 2006
    Location
    MA
    Posts
    649
    Franklin explained why this doesn't work ^^ See above.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...