C/C++ on Linux/Unix

Moderators: Lundin
Number of threads: 336
Number of posts: 663

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Linux ls command Posted by RichieMac on 27 Feb 2004 at 10:33 AM
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!
Report
Re: Linux ls command Posted by job4cse on 15 Mar 2004 at 11:31 AM
: 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;
}


Report
Re: Linux ls command Posted by rbrowning on 26 Dec 2010 at 6:35 AM
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



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.