scandir()

Ken Warner warner at scubed.UUCP
Fri Jul 1 03:41:58 AEST 1988


In article <1445 at uokmax.UUCP> sam at uokmax.UUCP (Sam L Falkner) writes:
>
>   Has anyone out there ever used the scandir() function?  I would
>really appreciate a program fragment that uses scandir (maybe to
>list all the filenames in a directory or something simple).  Be
>sure to include the declarations - they're probably the reason I'm
>messing up.  Please send me mail...
>   Many thanks...
>	- Sam Falkner

Here is a routine that uses scandir().  This is Sun 3-OS 3.4,5
specific.  The trick to using scandir() is to know how many entries are
in the directory before you make the call to scandir().  scandir()
just stuffs the array full of the entries into the the location pointed
to by the automatic and will blow away the stack if there isn't any
room.  Sort of a catch 22.  

Ken Warner
--------------------------------------------------------------------------------
#include <sys/param.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/dir.h>
#include <string.h>
#include <ctype.h>

select(direntry)
struct direct *direntry;
{

	if(!strcmp(".",direntry->d_name))
	    return (0);
	if(!strcmp("..",direntry->d_name))
	    return (0);
#ifdef DEBUG
	printf("select(): name = %s\n",direntry->d_name);
	fflush(stdout);
#endif
	return(1);
}

myls(name)
char *name;
{
/* must know how many entries in the directory before you make call */
	struct direct *(*namelist[1024]);
	int (*foo)();
	int (*bar)();
	int num_dir,i,j;
	char pathname[MAXPATHLEN],*getwd(),temp[80];
	extern alphasort();
	struct stat stbuf;

	foo = select;
	bar = alphasort;
	if(stat(name,&stbuf) == -1)
	{
	    perror(name);
	    return (-1);
	}
	if((getwd(pathname)) == (char *)0)
	{
	    perror(pathname);
	    return (-1);
	}
	if(stbuf.st_mode & S_IFDIR)
	{
	    if((num_dir = scandir(name,namelist,foo,bar)) == -1)
		perror(name);
	    chdir(name);
	    for(i=0;i<num_dir;i++)
	    {
		/*printf("%s\n",(*namelist)[i]->d_name);*/
		if(stat((*namelist)[i]->d_name,&stbuf) == -1)
		{
		    perror(name);
		    return (-1);
		}
		else if(stbuf.st_mode & S_IFREG)
		    printf("%s\n",(*namelist)[i]->d_name);
		else if(stbuf.st_mode & S_IFDIR)
		    printf("%s/\n",(*namelist)[i]->d_name);
		else if(stbuf.st_mode & S_IFLNK)
		    printf("%s@\n",(*namelist)[i]->d_name);
		fflush(stdout);
	    }
	    chdir(pathname);
	}
	else if(stbuf.st_mode & S_IFREG)
		printf("%s\n",name);
}



More information about the Comp.unix.wizards mailing list