Click here to Skip to main content
15,850,750 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
What I have to do is list all the files within a directory.
If a directory is shown then it also should print out the files within that directory.

At the moment I have:
C++
DIR *directory;
struct dirent *files;
char folderPath[] = "//home//unix//20//";


 // Make sure I can open the folder "test" otherwise throw an error
     if ((directory = opendir(folderPath)) == NULL)
     {
        printf("\nCouldn't Open Folder!\n");
        return 0;
     }
	// Loop around and check if the directory is another directory
	int i = 0;
		while ((files = readdir(directory)) != NULL)
		{
		  //printf("%s\n", files->d_name);
		  if (files->d_name 
		  i++;
		}
	printf("\n");


This code prints out all the files and folders within that directory.

What I need to do now, is find out if d_name is a directory and if it is, print out the contents within that directory.

Can some-one help me on how I can do this?
Thank-You
Posted
Updated 14-Oct-11 7:33am
v2

You have to look at the file attributes... A 'd' in the first field denotes a directory:
http://www.comptechdoc.org/os/linux/usersguide/linux_ugfilesp.html[^]

I believe stat() will give you the attributes in linux:
http://pubs.opengroup.org/onlinepubs/000095399/functions/stat.html[^]
 
Share this answer
 
Comments
Willtwinny 20-Oct-11 15:05pm    
I have had a read through, and I am still strugglying.
So far I got:
if (stat(files->d_name, &statbuf) == -1)
{
printf("%s\n", files->d_name);
}
But nothing is happening.
Albert Holguin 20-Oct-11 17:26pm    
what do you mean nothing is happening? you're not doing anything with the returned buffer (or structure)...
Willtwinny 3-Nov-11 0:32am    
Got it working in the end. Thanks :)
Check if d_type & DT_DIR and if so it is a directory.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900