4.4. Calculating number of records in a file

Figuring out how many records are in a stream file that has been organized into records is also quite simple. We just take the size of the file and divide it by the record length.

To simplify this slightly, I'm going to introduce another new API call. The fstat() API.

Here are the C and RPG prototypes:

     int fstat(int fildes, struct stat *buf)                        

     D fstat           PR            10I 0 ExtProc('fstat')            
     D   fildes                      10I 0 value                       
     D   buf                           *   value                       
   

I'm not going to explain the details of fstat(), since it's exactly like stat(), which we covered earlier.

The only difference between fstat() and the stat() API that we discussed in chapter 3, is that the fstat() API operates on a file descriptor, whereas the stat() API operates on a path name.

In other words, you use fstat() on a file that you've already opened, and you use stat() on a file that you don't need to open.

Once we've called fstat(), we can use the st_size subfield of the statds data structure to find the size of the stream file, and then divide it by our record length to find out how many records we have, like this:

     c                   if        fstat(fd: %addr(mystat)) < 0           
     c                   callp     die('fstat(): ' + %str(strerror(err))) 
     c                   endif                                            
                                                                          
     c                   eval      p_statds = %addr(mystat)               
     c                   eval      numrec = st_size / record_len