3.8. Renaming IFS objects

It's easy to change the name of an IFS object. The system gives us a rename() API which can be called to do that.

The rename() API operates on the file's link, rather than on the file's data. This means that doing a rename() is much more efficient than copying the file, and deleting the old copy! All it has to change is the link, not the data.

Here is both the C and RPG prototypes for the rename() API. Once again, I won't bore you with the details of translating from C to RPG, since it is very straightforward on this API.

      int rename(const char *old, const char *new)

     D rename          PR            10I 0 ExtProc('Qp0lRenameKeep')         
     D   old                           *   Value options(*string)            
     D   new                           *   Value options(*string)            

One detail that should be noted is that the external procedure name isn't "rename" as you might expect, it's "Qp0lRenameKeep". The reason for this is that there are actually two different rename APIs. The difference between them is what happens when the "new name" is already the name of another IFS object.

If you're calling Qp0lRenameKeep, and the "new name" already exists, the system will return an error, protecting you from accidentally deleting the existing file.

If, instead, you call Qp0lRenameUnlink, the system will unlink the existing filename, and then proceed with the renaming. I never use this option because I feel it's safer, and more intuitive, to use Qp0lRenameKeep. I can always call unlink() beforehand if I really want to unlink an existing file.

Calling rename() from an RPG program is easy. Just do something like this:

     c                   if        rename('/ifstest/oldsmellyfile.dat': 
     c                                    '/ifstest/newshinyfile.dat') < 0
     c                   callp     EscErrno(errno)
     c                   endif