cd.c 724 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. #include "sh.h"
  2. void cd(char **path)
  3. {
  4. char *pwd;
  5. char *oldpwd;
  6. if (ft_tabsize(path) > 1)
  7. {
  8. error_message("cd", "too many arguments", NULL);
  9. return ;
  10. }
  11. if ((pwd = get_tenv("PWD")) == NULL)
  12. pwd = get_pwd();
  13. oldpwd = get_tenv("OLDPWD");
  14. if (path[0] == NULL)
  15. path[0] = g_home != NULL ? g_home : ".";
  16. if (ft_strcmp(path[0], ".") == 0)
  17. path[0] = pwd;
  18. if (ft_strcmp(path[0], "-") == 0)
  19. path[0] = oldpwd;
  20. if (chdir(path[0]) == -1)
  21. error_message("cd", path[0], "no such file or directory");
  22. else
  23. {
  24. ft_setenv(ft_strjoin("OLDPWD=", pwd));
  25. ft_setenv(ft_strjoin("PWD=", get_pwd()));
  26. }
  27. }
  28. char *get_pwd(void)
  29. {
  30. char *pwd;
  31. pwd = (char *)malloc(sizeof(char) * 256);
  32. getcwd(pwd, 255);
  33. return (pwd);
  34. }