Re: ls lacking a feature?



John W. Krahn said:

Richard Heathfield wrote:
Bernard Liang said:

Well,

...you just want the directory name, not all the gubbins, so you thought
you'd try:

ls -l | grep ^d | tr -s ' ' | cut -d' ' -f9

This is slightly shorter:

ls -al | grep ^d | awk '{ print $9 }'

In my version of ls -l the file name is the eighth field and those don't
work very well if the names have spaces in them.

Below is an elementary C program to do the necessary. Yes, I accept that
it's a touch longer than the bash, awk and perl solutions. :-)

But once it's compiled and installed in /usr/local/bin, it's simplicity
itself to use:

lsdir path

or, if you want the current directory, simply

lsdir

Here's the code:

/* lsdir.c */

#include <stdio.h>
#include <string.h>

#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>


int is_dir(const char *name)
{
int is_directory = 0;
struct stat stbuf = {0};
if(stat(name, &stbuf) == -1)
{
fprintf(stderr, "lsdir: can't stat %s\n", name);
}
else
{
if(S_ISDIR(stbuf.st_mode))
{
is_directory = 1;
}
}
return is_directory;
}

void lsdir(const char *dir)
{
struct dirent *dp = NULL;
DIR *dfd = NULL;

if((dfd = opendir(dir)) == NULL)
{
fprintf(stderr, "lsdir: can't open %s\n", dir);
}
else
{
while((dp = readdir(dfd)) != NULL)
{
if(strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0)
{
if(is_dir(dp->d_name))
{
printf("%s\n", dp->d_name);
}
}
}
closedir(dfd);
}
}

int main(int argc, char **argv)
{
lsdir(argc > 1 ? argv[1] : ".");
return 0;
}

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
.



Relevant Pages