C

[C] 리눅스 명령어 ls, ls -a 구현

김호록님 2022. 11. 27. 16:01
if (strcmp(command1, "ls") == 0) { // ls
      command2 = strtok(NULL, " ");
      if (command2 == NULL){ // command = "ls"
        dirp = opendir(cwd);
        if(dirp == NULL) {
          fprintf(stderr, "opendir failed on '%s'", cwd);
        }
        while((dp = readdir(dirp)) != NULL) {
          if (strcmp(dp -> d_name, ".") == 0 || strcmp(dp -> d_name, "..") == 0)
    continue; // 디렉토리 이름이 . 이거나 .. 이면 출력 하지 않음 (숨김 파일)
          printf("%s\n", dp -> d_name);
        }
        if(closedir(dirp) == -1) perror("closedir");
      }
      else if (strcmp(command2, "-a") == 0) { // command = "ls -a"
        dirp = opendir(cwd);
        if(dirp == NULL) {
          fprintf(stderr, "opendir failed on '%s'", cwd);
        }
        while((dp = readdir(dirp)) != NULL) {
          printf("%s\n", dp -> d_name);
        }
        if(closedir(dirp) == -1) perror("closedir");
      }
    }