在c中实现ls,无限循环

时间:2016-06-09 19:47:57

标签: c

我试图在c中实现ls命令,当我尝试递归列出文件和文件夹时,我得到无限循环。我需要处理这个选项-l, -R, -a, -r and -t,我如何递归列出文件?

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;
}

当我用./ls . -R运行程序时,我得到无限循环。

允许的功能

allowed functions

1 个答案:

答案 0 :(得分: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;
}