: 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 <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
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\n", 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( "\t|" );
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\n", dbuf->d_name );
break;
case S_IFDIR:
printf( "\033[01;34m--%s \033[0m \n", dbuf->d_name ); //Display in Blue color
rec_open( dbuf->d_name, lev + 1 );
break;
default:
printf( "\n" );
}
}
closedir( dp );
chdir( cwd );
}
int main(int argc, char *argv[])
{
if (argc < 2)
rec_open( ".", 1 );
else
rec_open( argv[1], 1 );
return 0;
}