Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Linux ls command

I'm trying to rewrite the ls command for a small project. I don't really know where to begin so any help would be gratefully received.
Many thanx!

Comments

  • job4csejob4cse Member Posts: 29
    : I'm trying to rewrite the ls command for a small project. I don't really know where to begin so any help would be gratefully received.
    : Many thanx!
    :

    Hi,
    U can use the following code. This program opens the directory specified on the command line and list the entries recursively.




    #include
    #include
    #include
    #include
    #include

    static char wd[128];

    void rec_open( char *dname, int lev )
    {
    struct dirent *dbuf;
    DIR *dp;
    struct stat stbuf;
    char cwd[128];
    int i = strlen( dname );

    if (i > 1 && dname[i - 1] == '/')
    dname[i - 1] = 0;

    getcwd( cwd, sizeof (cwd) );
    // printf( "CWD = %s
    ", cwd );


    dp = opendir( dname );
    if (dp == NULL) {
    write( 1, "opendir ", 8 );
    perror( dname );
    return;
    }

    if (chdir( dname ) < 0) {
    write( 1, "chdir ", 6 );
    perror( dname );
    return;
    }

    while ((dbuf = readdir( dp ))) {
    if (! strcmp( dbuf->d_name, "." ) || ! strcmp( dbuf->d_name, ".." ))
    continue;

    for (i = 0; i < lev; ++i)
    printf( " |" );

    if (stat( dbuf->d_name, &stbuf ) < 0) {
    write( 1, "stat ", 5 );
    perror( dbuf->d_name );
    continue;
    }
    switch (stbuf.st_mode & S_IFMT) {
    case S_IFREG:
    printf( "--%s
    ", dbuf->d_name );
    break;
    case S_IFDIR:
    printf( "33[01;34m--%s 33[0m
    ", dbuf->d_name ); //Display in Blue color
    rec_open( dbuf->d_name, lev + 1 );
    break;
    default:
    printf( "
    " );
    }
    }
    closedir( dp );
    chdir( cwd );
    }

    int main(int argc, char *argv[])
    {
    if (argc < 2)
    rec_open( ".", 1 );
    else
    rec_open( argv[1], 1 );
    return 0;
    }


  • rbrowningrbrowning Member Posts: 1
    What is the point of

    while ((dbuf = readdir( dp ))) {
    if (! strcmp( dbuf->d_name, "." ) || ! strcmp( dbuf->d_name, ".." ))
    continue;

    The bit comparing "." with ".."?

    I'm working to write a small project doing the same command, but with the parameters -lR.

    Thanks
Sign In or Register to comment.