The persistent counter file

Finally, the last thing to modify is the utilities that manage the persistent counter file, read_file() and write_file().

The changes here are very simple. Instead of maintaining one counter value in the file (and in ASCII text at that), we maintain all of the counter values in the file, in binary (4 bytes per counter, native-endian format).

This implies that read_file() needs to read the entire file and populate all of the counter values, while write_file() needs to write the value of the counter that has changed, and leave the others alone. This also, unfortunately, implies that we can no longer modify the file “by hand” using a regular text editor, but instead must use something like spatch — this is fine, because we still have the ability to write() a number to the resource manager's “files.”

I've used the buffered I/O library (fopen(), fread(), fwrite())) in the implementation, and I fopen() and fclose() the file for each and every update. It would certainly be more efficient to use the lower-level I/O library (open(), read(), write(), etc.), and consider leaving the file open, rather than opening and closing it each time. I stayed with buffered I/O due to, yes, I'll admit it, laziness. The original used fopen() and fprintf() to print the counter value in ASCII; it seemed easier to change the fprintf() to an fseek()/fwrite().