2016-06-09 3 views
1

C에서 ls 명령을 구현하려고하는데 반복적으로 파일과 폴더를 나열하려고하면 무한 루프가 발생합니다. 이 옵션을 처리해야합니다. -l, -R, -a, -r and -t, 어떻게 재귀 적으로 파일을 나열 할 수 있습니까? 내가 ./ls . -R으로 프로그램을 실행할 때ls in c, 무한 루프

static int is_directory(const char *path) 
{ 
    struct stat statbuf; 

    if (stat(path, &statbuf) != 0) 
     return 0; 
    return S_ISDIR(statbuf.st_mode); 
} 

void  read_dir(char *dir_name, char *option) 
{ 
    DIR *dir; 
    struct dirent *entry; 

    dir = opendir(dir_name); 
    if (!dir) 
    { 
     my_putstr("ft_ls: cannot access "); 
     perror(dir_name); 
     return; 
    } 
    while ((entry = readdir(dir)) != NULL) 
    { 
     if (is_directory(entry->d_name) && options('R', option)) 
      read_dir(entry->d_name, option); 
     my_putstr(entry->d_name); 
     my_putchar('\n'); 
    } 
    closedir(dir); 
} 

int   main(int ac, char **av) 
{ 
    (void)ac; 
    read_dir(av[1], av[2]); 
    return 0; 
} 

나는 무한 루프를 얻을.

허용 기능

allowed functions

+2

1) 'entry-> d_name'이 "."일 때 재발생 할 필요가 없습니다. 또는 ".."2) 재귀 할 때 현재 작업 디렉토리를 변경할 필요가 있습니다. – chux

+0

더 나아 가기 전에'main'에 대한 간단한 설명. 종래의 서명인'int main (int argc, char * argv [])'를 사용하는 것이 더 좋았고,'ac' (지금은'argc')를 사용하기 전에 충분한 인수를 확인했다면 컴파일러를 이길 필요가 없었을 것입니다 '(void) ac; '로 경고 @ –

+0

@WeatherVane 내가 사용할 수있는 것에 대한 제한이 있으며 학교에서 요구하는대로'main '의 서명이 그렇게되어야한다. –

답변

1

내가 먼저 현재 폴더에있는 모든 것을 나열이 while loops을 사용하기로 결정 한 후 다시이 시간 폴더를 검사하고, 재귀 read_dir 함수를 호출을 참조하십시오.

#include <dirent.h> 
#include "libft.h" 
#include <stdio.h> 
#include <sys/stat.h> 

static int is_directory(const char *path) 
{ 
    struct stat statbuf; 

    if (stat(path, &statbuf) != 0) 
     return 0; 
    return S_ISDIR(statbuf.st_mode); 
} 

void  read_dir(char *dir_name, char *option) 
{ 
    DIR *dir; 
    struct dirent *entry; 

    dir = opendir(dir_name); 
    if (!dir) 
    { 
     my_putstr("ft_ls: cannot access "); 
     perror(dir_name); 
     return; 
    } 
    while ((entry = readdir(dir)) != NULL) 
    { 
     my_putstr(entry->d_name); 
     my_putchar('\n'); 
    } 
    closedir(dir); 
    dir = opendir(dir_name); 
    if (!dir) 
    { 
     my_putstr("ft_ls: cannot access "); 
     perror(dir_name); 
     return; 
    } 
    while ((entry = readdir(dir)) != NULL && options('R', option)) 
    { 
     if (is_directory(entry->d_name) && (!(my_strncmp(entry->d_name, ".", 1) == 0))) 
      read_dir(entry->d_name, option); 
    } 
    closedir(dir); 
} 

int   main(int ac, char **av) 
{ 
    if (ac == 3) 
     read_dir(av[1], av[2]); 
    else if (ac == 2 || ac > 3) 
     //call --help function 
    else 
     read_dir(".", ""); 
return 0; 
}