Code Snippets
What's That?
I am using it actively
I planning to use/learn it
I don't plan to lean/use it
5th option
Home :: Programming :: Code Snippets :: Cpp :: Listing Files Under Linux

[ Listing Files Under Linux ]

If you have ever wondered how to list all files that are in a certain folder on your computer using a little and easy function then you have clicked on the right link! Compared to the Windows solution, enumerating files under Linux is as easy as saying "Good Morning".

The function we have indirectly been talking about is scandir(..). It's quite powerful but for our purposes we won't need all its parameters:

#include <dirent.h>

int scandir(const char *dir, struct dirent ***namelist,
  int(*select)(const struct dirent *),
  int(*compar)(const struct dirent **, const struct dirent **));

The first parameter is the path of the directory we would like to scan, either relative to the current one or absolute. namelist is a pointer to an array made out of pointers which will finally store the entries. The third parameter, a function pointer, might be 0 but if set it will be called on every entry. When your select function returns a non-zero integer the current entry will be stored in the namelist array. The compar might be 0 too but if set it's the comparison function for qsort(..). scandir returns the number of entries listed or -1 in case of an error.

After this little theory section, we'll check out a real example for _real_ men:

#include <dirent.h>
#include <iostream>

using namespace std;


struct dirent **nameList;
int numberOfFiles;

//scan the current directory
numberOfFiles = scandir("./", &nameList, 0, 0);

if (numberOfFiles >= 1)
   //go through all files
   while (numberOfFiles--)
      //only normal files, not dots (. and ..)
      if (strcmp(nameList[numberOfFiles]->d_name, ".")  &&
          strcmp(nameList[numberOfFiles]->d_name, ".."))
             //output every file
             cout << "file: "<< nameList[numberOfFiles]->d_name << endl;

             //don't forget to free used space

   //free used resource

That's it! You'll see all files listed of the current folder. Please always remember to free every array entry and the namelist itself. We don't want to "stress" our pour little kernel... Happy C0ding!

 Last edited 2003-08-19 20:57:39 by André Stein - printable version
» copyright by andré stein
» using stCM v1.0
» steinsoft.net revision 5.0