7.5. Opening Directories

Now that we know how to create and delete directories, and change our current directory, we also need to know how to read the contents of a directory.

The process of reading directories in an RPG program will require you to use 3 different APIs. They are opendir(), which opens the directory, readdir() which reads the next entry from a directory and closedir() which closes the directory when you're finished.

The opendir() API is similar in some ways to the open() API. It accepts a parameter that tells the name of a directory to open, and it returns a handle that can be used to read through that directory.

Here is the C-language prototype for the opendir() API:

     DIR *opendir(const char *dirname)  

We know that the "DIR *" means that it returns a pointer to a "DIR". But what data type is a "DIR"? We could figure that out -- if you hunt through the C header members, you'd eventually find it. But, as it turns out, we don't need it! All we need to do with the return value from opendir() is pass it as a parameter to the readdir() and closedir() APIs. Therefore, we don't care what the pointer points to! We can just treat it as a pointer.

When this API fails, it will return a *NULL pointer, and we can then check errno to find out which error occurred.

Therefore, the prototype for the opendir() API in RPG looks like this:

     D opendir         PR              *   EXTPROC('opendir')       
     D  dirname                        *   VALUE options(*string)   

When we want to open a directory, we simply pass the directory name as a parameter. For example, if our goal was to read the contents of the root directory of the IFS, we might write code that looks like this:

     D d               S               *                    
     c                   eval      d = opendir('/')         
     c                   if        d = *NULL                
     c                   callp     EscErrno(errno)          
     c                   endif