PDA

View Full Version : finding files in a directory



Strut
01-27-2002, 05:49 PM
I was just curious as to how I would run through the files in a directory and print out each file name.

thanks.

starX
01-27-2002, 09:32 PM
ls -a on the command line.

Are you looking to do this in a script or a compiled program?

starX
www.axisoftime.com

mix0matt
01-27-2002, 11:08 PM
read the man page ($man scandir) for scandir. That should give you the info you want for your system.


int scandir (const char *dir, struct direct ***namelist,
int (*select) (const struct direct *),
int (*compar) (const struct direct **, const struct direct **));

here's a rough example (notethat if select is passed a NULL arguement, all names under the directory are placed in the arrary of direct structures.


#include <sys/dir.h>
#include <sys/param.h>
#include <stdio.h>
#include <string.h>

extern int alphasort ();

char pathname[MAXPATHLEN];

int main ()
{
int count, i;
struct direct** files;

strcpy (pathname, "/home/matt");
count = scandir (pathname, &files, NULL, alphasort);
if (count <= 0) {
fprintf (stderr, "No files in the directory \n");
exit (0);
}
printf ("Number of files = %d\n", count);
for (i = 1; i < count + 1; ++i )
printf ("%s\n", files[i-1]->d_name);

return 0;
}Let me know if you don't understand anything after you read the man page...

Strut
01-28-2002, 07:15 PM
thanks to both of you!