cd.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include "sh.h"
  2. /*
  3. ** Check there is only one argument
  4. ** Retrieve PWD and OLDPWD env var
  5. ** Get path replacement for 'cd', 'cd .', 'cd -'
  6. */
  7. void cd(t_e *e, char **paths)
  8. {
  9. char *pwd;
  10. char *oldpwd;
  11. char *path;
  12. if (ft_tabsize(paths) > 1)
  13. {
  14. error_message("cd", "too many arguments", NULL);
  15. return ;
  16. }
  17. path = paths[0];
  18. if ((pwd = get_tenv(e, "PWD")) == NULL)
  19. pwd = get_pwd();
  20. oldpwd = get_tenv(e, "OLDPWD");
  21. if (paths[0] == NULL)
  22. path = e->home != NULL ? e->home : ".";
  23. if (ft_strcmp(paths[0], ".") == 0)
  24. path = pwd;
  25. if (ft_strcmp(paths[0], "-") == 0)
  26. path = oldpwd;
  27. apply_cd(e, path, pwd);
  28. }
  29. /*
  30. ** Change directory with 'path' var
  31. ** If directory changed, change PWD and OLDPWD env var
  32. */
  33. void apply_cd(t_e *e, char *path, char *pwd)
  34. {
  35. if (chdir(path) == -1)
  36. error_message("cd", path, "no such file or directory");
  37. else
  38. {
  39. ft_setenv(e, ft_strjoin("OLDPWD=", pwd));
  40. ft_setenv(e, ft_strjoin("PWD=", get_pwd()));
  41. }
  42. }
  43. /*
  44. ** Get current path
  45. */
  46. char *get_pwd(void)
  47. {
  48. char *pwd;
  49. pwd = (char *)malloc(sizeof(char) * 256);
  50. getcwd(pwd, 255);
  51. return (pwd);
  52. }