2011年12月12日 星期一

仿指令: ls

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

#define DEBUG_ENV

#define TARGET_PATH "/home/ecs/test/t7"

typedef struct root_t
{
    int depth;
    char rootname[256];
    struct root_t* next;
} node;


node* create_node(int depth, char *name)
{
    node *n = (node*)malloc(sizeof(node));
    n->depth=depth;
    strcpy(n->rootname, name);
    n->next = NULL;

    return n;
}

void insert_node(node* n1, node* n2)
{
    if (n2==NULL)
        return;
    n2->next = n1->next;
    n1->next = n2;
    return;
}

void free_lists(node* lists)
{
    if (lists->next != NULL)
    {
        free_lists(lists->next);
    }

    free(lists);
}

void print_lists(node* lists)
{
    node* n = lists;

    while (n != NULL)
    {
        printf("depth=%d, nmae=%s\n", n->depth, n->rootname);
        n = n->next;
    }
    printf("\n");
}

node *printdir(char* dir, int depth, node *root)
{
    DIR* str=opendir(dir);
    struct stat statbuf;
    struct dirent* entry;
    node *leaf;

    if(str==NULL)
    {
        printf("the direction is not valid");
        return;
    }
    chdir(dir);
    while((entry=readdir(str))!=NULL)
    {
        lstat(entry->d_name,&statbuf);
        leaf=create_node(depth, entry->d_name);
        //printf("leaf->name=%s\n", leaf->rootname);
        if(S_ISDIR(statbuf.st_mode))
        {
            if(strcmp(".",entry->d_name)==0||strcmp("..",entry->d_name)==0)
                continue;
            //printf("DIR  %d, %8s, %8ld\n", depth, entry->d_name, entry->d_ino);
            root=printdir(entry->d_name,depth+1, leaf);
            print_lists(leaf);
        }
        else
        {
            //printf("File %d, %8s, %8ld\n", depth, entry->d_name, entry->d_ino);
            if (leaf->depth > depth)
                insert_node(root, leaf);
            else if (leaf->depth == depth)
                print_lists(leaf);
        }
    }
    chdir("..");
    closedir(str);
    free_lists(leaf);
    return leaf;
}

int main(void)
{
    printdir(TARGET_PATH, 1, NULL);
    return 0;
}
http://daviddr.blogspot.com/2009/10/blog-post_2637.html
Here

沒有留言:

張貼留言