Chinaunix

标题: 如何在程序中调用cd命令 [打印本页]

作者: shenzhengxuan    时间: 2006-12-04 14:52
标题: 如何在程序中调用cd命令
linux下有个system函数可以用来调用各种命令,但执行
system("cd /");
却没有正确执行。请问各位大侠如何调用cd命令来改变路径呢?非常感谢
作者: mq110    时间: 2006-12-04 15:22
man chdir
作者: owenyang1984    时间: 2006-12-04 15:25
什么系统
作者: shenzhengxuan    时间: 2006-12-04 15:28
谢谢mq110
不能通过system调用来实现么?redhat9.0。
作者: wuzhao    时间: 2006-12-04 16:07
system调用是通过fork子进程后exec实现的
作者: mq110    时间: 2006-12-04 17:29
原帖由 shenzhengxuan 于 2006-12-4 15:28 发表
谢谢mq110
不能通过system调用来实现么?redhat9.0。


正如楼上的所说,system不能改变当前进程的current working directory,改变的只是子进程的current working directory不影响当前进程.
作者: duanjigang    时间: 2006-12-05 13:13
要更改目录吗,为什么要用system函数,而不这样

  1. #ifndef _WIN32
  2. #include <unistd.h>
  3. #endif
  4. #include <stdio.h>
  5. int main(void)
  6. {
  7. char olddir[100],newdir[100];
  8. char *old = getcwd(olddir, 100);
  9. char * new ;
  10. printf("current dir is: %s\n", old);
  11. chdir("../../");
  12. new = getcwd(newdir, 100);
  13. printf("change dir to : %s\n", new);
  14. chdir(olddir);
  15. getcwd(newdir, 100);
  16. printf("back to: %s\n", newdir);
  17. }
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2