The opendir(), readir() and closedir() library functions supported by C library can be used to get the names of files presented in a directory. The readdir() function should be invoked repeatedly to get all the files until it returns NULL. It returns a pointer to a structure dirent.

struct dirent {
   ino_t          d_ino;       /* inode number */
   off_t          d_off;       /* offset to the next dirent */
   unsigned short d_reclen;    /* length of this record */
   unsigned char  d_type;      /* type of file */
   char           d_name[256]; /* filename */
};

The following example program takes a directory name as command line arguments and prints the names of all file names along with the type of file. If no argument is provided, it automatically takes current directory as the argument.

[neo@techpulp ~]# cat dirlist.c
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

char* type_to_str(unsigned char type)
{
switch(type) {
case DT_REG:
return "Regular File";
case DT_DIR:
return "Directory";
case DT_FIFO:
return "Named pipe or FIFO";
case DT_SOCK:
return "UNIX Domain Socket";
case DT_CHR:
return "Character Device";
case DT_BLK:
return "Block Device";
}
return "Unknown";
}

int main(int argc, char *argv[])
{
char *dname = "."; /* current directory */
DIR *d;
struct dirent* de;

if(argc >= 2) dname = argv[1];

d = opendir(dname);
if(!d) {
perror("opendir");
return 1;
}

while((de = readdir(d))) {
printf("%30s\t%s\n", de->d_name, type_to_str(de->d_type));
}

closedir(d);

return 0;
}
[neo@techpulp ~]#

Let us compile and execute the example program.

[neo@techpulp ~]# gcc dirlist.c -o dirlist
[neo@techpulp ~]# ./dirlist
..  Directory
dirlist.c  Regular File
.  Directory
dirlist  Regular File
[neo@techpulp ~]#