prev up next   top/contents search

comp.lang.c FAQ list · Question 19.20

Q: How can I read a directory in a C program?


A: See if you can use the opendir and readdir functions, which are part of the POSIX standard and are available on most Unix variants. Implementations also exist for MS-DOS, VMS, and other systems. (MS-DOS also has FINDFIRST and FINDNEXT routines which do essentially the same thing, and MS Windows has FindFirstFile and FindNextFile.) readdir returns just the file names; if you need more information about the file, try calling stat. To match filenames to some wildcard pattern, see question 13.7.

Here is a tiny example which lists the files in the current directory:

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

main()
{
	struct dirent *dp;
	DIR *dfd = opendir(".");
	if(dfd != NULL) {
		while((dp = readdir(dfd)) != NULL)
			printf("%s\n", dp->d_name);
		closedir(dfd);
	}
	return 0;
}
(On older systems, the header file to #include may be <direct.h> or <dir.h>, and the pointer returned by readdir may be a struct direct *. This example assumes that "." is a synonym for the current directory.)

In a pinch, you could use popen (see question 19.30) to call an operating system list-directory program, and read its output. (If you only need the filenames displayed to the user, you could conceivably use system; see question 19.27.)

References: K&R2 Sec. 8.6 pp. 179-184
PCS Sec. 13 pp. 230-1
POSIX Sec. 5.1
Schumacher, ed., Software Solutions in C Sec. 8


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North