2.2. Closing a file with the close() API

If your head is spinning after reading about the open() API, you'll be glad to know that the close() API is comparatively simple.

The close() API is used to close a file that we opened when we called the open() API. Here is the C language prototype for close(), as it is listed in IBM's UNIX-type APIs manual:

      int close(int fildes);

Simple, yes? The "int" is the return value. The "close" is the name of the procedure. The "int fildes" is the only parameter to the procedure, and it's just an integer, which is "10I 0" in RPG.

So, the RPG prototype will look like this:

     D close           PR            10I 0 extproc('close')
     D   fildes                      10I 0 value

See? It returns a "10I 0", because the C prototype returned an "int". It accepts one parameter, which is also a "10I 0" because the C prototype's only parameter was an "int". The parameter is passed by value because we don't want to pass the address, and we use "extproc()" to make sure the compiler doesn't try to call "CLOSE" instead of "close".


There's one small problem. This same close() API is used by both socket connections (TCP/IP communications API) and also by the IFS APIs that we're using. That's a problem because if you ever tried to use both sockets and IFS in the same program, the definitions would conflict, and the program wouldn't compile.

So, we're going to use a little "compiler directive" magic to make sure that the two close() prototypes never conflict, by making the prototype look like this:

     D/if not defined(CLOSE_PROTOTYPE)
     D close           PR            10I 0 extproc('close')
     D   fildes                      10I 0 value

And then, when the day comes that we make a header member for sockets, we'll have to remember to also put that same /define logic in the sockets header member. Do you see how it works? Pretty cool eh?

Here's an example of calling the close() API:

      c                   callp     close(fd)