This shows the sub-directories in the current path.
It's not a lot different to something likeā¦
ls-l | grep ^d | cut xxx
Where xxx is the position of the filename but unlike the shell code, it isn't subject to the vagaries of the ls command.
/* ---------------------------------------------
Name: sdr
Purpose: Displays the directories subservient
to the current directory.
------------------------------------------ */
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
main(int argc, char *argv[]){
char *DirectoryName;
DIR *ThisDirectory; /* List of directory contents */
struct dirent *ThisEntry; /* Entries in the directory list */
struct stat ThisEntryStatus; /* Directory status entries */
switch (argc)
{
case 1: DirectoryName = (char *)".";
break;
default: printf("sdr must be invoked from within the desired path.\n");
break;
}
if((ThisDirectory = opendir(DirectoryName)) == NULL)
{
printf("'%s' is not a valid path \n", DirectoryName);
return(1);
}
/* ------------------------------------------------------------
Loop through the struct pulling out a pointer
to a directory entry on each pass.
Put this entry into a ThisEntryStatus struct
and if that succeeds, check to see if this is a directory.
If it is, check that it isn't the current (.) or parent (..)
entry. if not, print the directory name...
--------------------------------------------------------- */
while (ThisEntry = readdir(ThisDirectory))
{
if (stat(ThisEntry->d_name, &ThisEntryStatus) == 0)
if (ThisEntryStatus.st_mode & S_IFDIR)
if (strcmp(ThisEntry->d_name, ".") != 0)
if (strcmp(ThisEntry->d_name, "..") != 0)
printf("%s\n", ThisEntry->d_name);
}
return closedir(ThisDirectory);
}