Go back to Previous Directory in Linux using a C program

旧街凉风 提交于 2019-12-20 04:38:28

问题


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-program?


回答1:


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.




回答2:


You can use the chdir function for this:

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



回答3:


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);


来源:https://stackoverflow.com/questions/7089834/go-back-to-previous-directory-in-linux-using-a-c-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!