lsflib/src/getdir.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Thu, 16 Apr 2009 12:49:13 +0200
changeset 56 966ad681f25d
parent 9 c3fecc82ade6
child 77 49e0babccb23
permissions -rw-r--r--
Short Description * duff.c Duffs Device, a fast copy algorithm * crypt.c the Salt was to short. * files.c massive directory creation * fork.c a small fork demo committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 * test/demos/lsflib/src/getdir.c
 * Copyright (C) 2008 Markus Broeker
 */

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>

#include <lsf.h>

int isDir (char *filename)
{
    struct stat buf;

    if (!stat (filename, &buf))
        return (S_ISDIR (buf.st_mode));

    return 0;
}

int isFile (char *filename)
{
    struct stat buf;

    if (!stat (filename, &buf))
        return (S_ISREG (buf.st_mode));

    return 0;
}

void getdir (char *root, int recursive)
{
    struct dirent *entry;
    DIR *directory;
    char *list;

    if (!isDir (root))
        return;

    if ((directory = opendir (root)) == NULL) {
        perror (root);
        return;
    }

    while ((entry = readdir (directory))) {
        list = (char *)malloc (strlen (root) + 1 + strlen (entry->d_name) + 1);

        if (list == NULL) {
            perror ("malloc");
            return;
        }

        sprintf (list, "%s/%s", root, entry->d_name);

        if (!strcmp (entry->d_name, "."))
            continue;
        if (!strcmp (entry->d_name, ".."))
            continue;
        if (isDir (list)) {
            printf ("Directory: %s\n", list);
            if (recursive)
                getdir (list, recursive);
            continue;
        }

        printf ("%s\n", list);
    }

    free (list);
    closedir (directory);
}