Here is borrowed from Mr.Ritchie
Code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define NAME_MAX 10
typedef struct {
int fd;
char name [NAME_MAX + 1];
} Dirent;
typedef struct {
int fd;
Dirent d;
} Dir;
/* that's just for portability (Mohsen)*/
/* Now you can use 3 functions: */
DIR *opendir (char* dirname);
Dirent *readdir (DIR *dfd);
void closedir (char*, struct stat*)
/*
The Dirent structure contains the inode
number and the name. The maximium length of a file
name component is NAME_MAX , which
is a SYSTEM DEPENDENT value. opendir returns
a pointer to a structure called DIR,
analogous to FILE, which is used
by readdir and closedir.
*/
Now you may use stat system call to determine if your name is a directory (take a look at manual page of stat).
Code:
Dirent *dp;
DIR *dfd;
if ((dfd = opendir ("MyDirName")) == NULL)
exit (1);
/* readdir returns
file names in directory. dp->name may be `.'
or `..' which should be ignored. */
while ((dp = readdir (dfd) != NULL) {
if (strcmp (dp->name, ".") == 0 || strcmp (dp->name, "..") == 0)
continue;
printf ("file: %s\n", dp->name);
}
P.S.
I'va wrote it in a hurry so check out the man pages on any question.