Search code examples
csystem

Can i work in subdirectories with the system() command?


I am some kind of newbie in programming and i was just asking myself, if i can switch between folders with the system() command and work there, just like i can do when i type in the commands in the terminal by myself.

It's not that kind of very important problem, but it would be nice to know.


Solution

  • You can do the following possibly: system ("cd /path/to/dir; pwd"); . Which is, separate the commands via a semicolon. Although once the function returns the directory change will not be applicable anymore. This is because the system command spawns a new process to execute whatever you have put in the arguments. Once the process terminates things are lost. Therefore, this directory change is applicable to the process which system spawns, and not to the working directory of the program which calls system .

    Although, depending on what is your purpose, I would recommend seeing fork, exec family, and chdir in a combination.