hey can someone suggest the best way to get the list of files in a directory. i only need files no need directories.

given a folder, i want to write a program that gets all the files in it. its part of a much bigger program. appreciate any help.

many thanks for the people that keep replying to my post. i've been having deadline aftrer deadline and i've been meeting them thanks to help i got from this forum.
cheers
drjay!

theres no standard way to do this. it totally depends on your environment.

for instance, a POSIX solution might look like this

#include <stdio.h>
#include <dirent.h>

int main (void)
{
   DIR *dir_ptr;
   struct dirent *entry_ptr;

   if (dir_ptr = opendir ("./"))
   {
      while (entry_ptr = readdir (dir_ptr))
          printf("%s\n",entry_ptr->d_name);
      closedir (dir_ptr);
   }
   else
      printf ("Can not open directory\n");

   return 0;
}

while the Windows solution could be done with the API commands "FindFirstFile" and "FindNextFile"
http://msdn.microsoft.com/en-us/library/aa364418(VS.85).aspx

another way to do it would be to capture the output of the "ls" or the "dir" command using popen() ...

i know this works for GCC on Linux, and i assume it will work for windows, but i don't know for certain. try replacing "dir /b" (or whatever variant you want to use) with the "ls" command.

#include <stdio.h>

#define LIST_COMMAND	"ls"

int main (void)
{
	char buffer[1024];
	char *line_p; 
	FILE *dirList_p;

	if (dirList_p = popen(LIST_COMMAND, "r")) 
	{
		while(line_p = fgets(buffer, sizeof(buffer), dirList_p))
			printf(buffer);
		pclose(dirList_p);
	}
	else 
		return -1;
		
	return 0;
}
This article has been dead for over six months. Start a new discussion instead.