开发者

Go back to Previous Directory in Linux using a C program

I am in the directory /home/destination I need to go back to the /home directory. Any ideas on how to implement this using a C-prog开发者_如何学Goram?


A program can only change its own environment. Thus, the program can chdir but it will not change the current directory of the parent. That's why cd can't be implemented as an external command.


You can use the chdir function for this:

chdir(".."); /* change current working directory, go one level up */


If you'd like to go level up chdir(".."); will do the work. But if you'd like to have behaviour like cd - then you should use this code:

char *prev;
prev = getcwd(prev, 0); /*POSIX.1-2001: will malloc enough memory*/
/*fail if prev is NULL, do something*/
chdir(prev);
free(prev);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜