Path: utzoo!attcan!uunet!lll-winken!lll-lcc!mordor!joyce!ames!scubed!warner From: warner@scubed.UUCP (Ken Warner) Newsgroups: comp.unix.wizards Subject: Re: scandir() Keywords: scandir catch-22 Message-ID: <799@scubed.UUCP> Date: 30 Jun 88 17:41:58 GMT References: <1445@uokmax.UUCP> Reply-To: warner@scubed.UUCP (Ken Warner) Organization: S-Cubed Lines: 91 In article <1445@uokmax.UUCP> sam@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 #include #include #include #include #include #include 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;id_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); }