|
| 1 | +#include "header.h" |
| 2 | + |
| 3 | +void change_directory(char** arg, int index) |
| 4 | +{ |
| 5 | + struct passwd *password; |
| 6 | + char *home; |
| 7 | + char directory_path[SIZE]; |
| 8 | + int flag = 0; |
| 9 | + int home_len = 0; |
| 10 | + |
| 11 | + password = getpwuid(getuid()); |
| 12 | + home = password -> pw_dir; |
| 13 | + home_len = strlen(home); |
| 14 | + |
| 15 | + if(index >= 3) |
| 16 | + { |
| 17 | + printf("cd: too many arguments\n"); |
| 18 | + } |
| 19 | + else if(index == 2) |
| 20 | + { |
| 21 | + if(!strncmp("~", arg[1], 2)) |
| 22 | + flag = 1; |
| 23 | + if(!strncmp("-", arg[1], 2)) |
| 24 | + flag = 2; |
| 25 | + if(!strncmp("~-", arg[1], 3)) |
| 26 | + flag = 3; |
| 27 | + if(!strncmp("~/", arg[1], 2)) |
| 28 | + flag = 4; |
| 29 | + |
| 30 | + switch(flag) |
| 31 | + { |
| 32 | + case 1 : |
| 33 | + chdir(home); |
| 34 | + break; |
| 35 | + case 2 : |
| 36 | + printf("%s", previous_directory); |
| 37 | + if(strcmp("\0", previous_directory)) |
| 38 | + printf("\n"); |
| 39 | + case 3 : |
| 40 | + if(!strcmp("\0", previous_directory)) |
| 41 | + { |
| 42 | + printf("cd: OLDPWD not set\n"); |
| 43 | + break; |
| 44 | + } |
| 45 | + else |
| 46 | + { |
| 47 | + chdir(previous_directory); |
| 48 | + break; |
| 49 | + } |
| 50 | + case 4 : |
| 51 | + strcpy(directory_path, home); |
| 52 | + strcat(directory_path, arg[1] + 1); |
| 53 | + if(chdir(directory_path)) |
| 54 | + printf("cd: %s: No such file or directory\n", directory_path); |
| 55 | + break; |
| 56 | + default : |
| 57 | + if(chdir(arg[1])) |
| 58 | + printf("cd: %s: No such file or directory\n", arg[1]); |
| 59 | + } |
| 60 | + } |
| 61 | + else |
| 62 | + { |
| 63 | + chdir(home); |
| 64 | + } |
| 65 | + |
| 66 | + if(!strncmp(current_directory, "~", 1)) |
| 67 | + { |
| 68 | + strcpy(previous_directory, home); |
| 69 | + strcat(previous_directory, current_directory + 1); |
| 70 | + } |
| 71 | + else |
| 72 | + strcpy(previous_directory, current_directory); |
| 73 | + |
| 74 | + getcwd(current_directory, sizeof(current_directory)); |
| 75 | + if(!strncmp(current_directory, home, home_len)) |
| 76 | + { |
| 77 | + strcpy(directory_path, current_directory); |
| 78 | + strcpy(current_directory, "~"); |
| 79 | + strcat(current_directory, directory_path + (home_len)); |
| 80 | + } |
| 81 | + |
| 82 | + return; |
| 83 | +} |
| 84 | + |
| 85 | +/* |
| 86 | + ~ : HOME (1) |
| 87 | + - : OLDPWD로 이동 (2) |
| 88 | + 키자마자 바로하면 cd: OLDPWD not set |
| 89 | + ~- : echo 없이 OLDPWD 이동 (3) |
| 90 | + ~/[...] : 디렉토리 이동 (4) |
| 91 | + default : 디렉토리 그대로 chdir (0) |
| 92 | + |
| 93 | + 마지막에 current_directory와 previous_directory 세팅해 주기 |
| 94 | + $HOME 이면 current_directory "~" 변환 |
| 95 | + */ |
| 96 | + |
0 commit comments