Using chdir() to change directory from Terminal

落花浮王杯 提交于 2019-12-02 00:57:14

What you are attempting to do can't be done. The current working directory is a per-process attribute.

If you run a program which changes its cwd, it does not affect any other processes, except for any children it might create after the chdir().

The correct way to change the terminal's working directory is to use the cd command which the shell executes on your behalf and remains within the same process. That is, cd is one of several commands that the shell does not fork(); this makes the cd command work as expected.

sourceing a shell file makes it run within the shell's process. However, if you were to run the script without source, you'd find there was the exact same problem as with a C program: the shell forks to create a process for the script to run, it runs and then exits, and then the shell continues, but without its cwd changed.

user3629249

this is the way to change the current working directory in C

this needs the unistd.h header file to be included

if( 0 != chdir( "pathToNewDirectory" ) )
{ // then chdir failed
    perror( "chdir failed" );
   // handle error
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!