日期:2014-05-16  浏览次数:20721 次

chdir没起作用?
chdir问题
为何使用了chdir函数之后,使用getcwd函数获取当前目录似乎是我欲改变的目录,但使用PWD查看当前工作目录并没有改变呢?代码如下:
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h> //?
#include<unistd.h>
#include<stdio.h>

#define SIZE 30


int main()
{
  char newpath[SIZE];
  char buf[SIZE];
  /*get the path of present at first*/
  if(getcwd(buf,SIZE)==NULL)
  {
  printf("error ,getcwd failed!\n");
  return -1;
  }
  printf("cwd = %s\n",buf);
  /*input the path that you want change to */
  printf("Input the new pathname[<30 strings]:\n");
  gets(newpath);
  if(chdir(newpath) == -1)//change to the directory you want
  {
  printf("error,change directory failed!\n");
  return -1;
  }
  printf("ok,change directory successful!\n");
  if(getcwd(buf,SIZE)==NULL)
  {
  printf("error ,getcwd failed!\n");
  return -1;
  }
  printf("cwd = %s\n",buf);
  return 0;
}求解中,谢谢

------解决方案--------------------
说明:chdir函数用于改变当前工作目录。调用参数是指向目录的指针,调用进程需要有搜索整个目录的权限。每个进程都具有一个当前工作目录。在解析相对目录引用时,该目录是搜索路径的开始之处。如果调用进程更改了目录,则它只对该进程有效,而不能影响调用它的那个进程。在退出程序时,shell还会返回开始时的那个工作目录。