Junius L
Junius L

Reputation: 16142

Implementing ls in c, infinite loop

I'm trying to implement ls command in c, when I try to recursively list files and folders, I get infinite loop. I need to handle this options -l, -R, -a, -r and -t, How can I recursively list files?

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

when I run the program with ./ls . -R I get infinite loop.

Allowed functions

allowed functions

Upvotes: 1

Views: 320

Answers (1)

Junius L
Junius L

Reputation: 16142

I have decided to use two while loops, first listing everything in the current folder, then read again this time checking for folders, and recursively calling read_dir function.

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

Upvotes: 1

Related Questions