Simulation tree command in C

Posted by Ecle on Stack Overflow See other posts from Stack Overflow or by Ecle
Published on 2012-09-13T03:37:07Z Indexed on 2012/09/13 3:37 UTC
Read the original article Hit count: 189

Filed under:
|
|
|
|

I have to create the simulation of tree command in C, this is my current code:

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


main(int argc, char *argv[]){

int i;

if(argc < 2){
    printf("\nError. Use: %s directory\n", argv[0]);
    system("exit");
}
for(i=1;i<argc;i++)
    //if(argv[i][0] != '-')
        tree(argv[i]);
}

tree(char *ruta){

DIR *dirp;
struct dirent *dp;
static nivel = 0;
struct stat buf;
char fichero[256];
int i;

if((dirp = opendir(path)) == NULL){
    perror(path);
    return;
}

while((dp = readdir(dirp)) != NULL){
    printf(fichero, "%s/%s", path, dp->d_name);
    if((buf.st_mode & S_IFMT) == S_IFDIR){
        for(i=0;i<nivel;i++)
            printf("\t");
        printf("%s\n", dp->d_name);
        ++nivel;
        tree(fichero);
        --nivel;
    }

}
}

Apparently, it works! (due to it compiles correctly) But I don't why. I can't pass the correct arguments to execute this. Thank you so much, people.

© Stack Overflow or respective owner

Related posts about c

    Related posts about linux