I'm writing functions that take the checksum of two different things: one, a file; and two, an archive entry a la the BSD libarchive library. I borrowed the checksum code from GNU's coreutils.
My code for doing a checksum on a file reads from its source like this:
unsigned char buf[BUFLEN];
size_t bytes_read;
FILE *fp;
...
while ((bytes_read = fread (buf, 1, BUFLEN, fp)) > 0) { ... }
In my code for reading from an archive entry, the corresponding code looks like
struct archive *ar;
unsigned char buf[BUFLEN];
ssize_t bytes_read;
...
while ((bytes_read = archive_read_data(ar, buf, sizeof(buf))) > 0) { ... }
As it stands, I'll have to have two different functions here, even though most of the code is the same. I don't quite see how to do it by passing a function pointer, since fread and archive_read_data don't even have the same number of arguments. (I guess I could start by using read(2) instead of fread(3), but I'm not sure that's a productive way to proceed.)
Is there a nice method to avoid code duplication here? Aside from trying to do it with function pointers, I could do it by putting the identical code pieces in separate files, then
#including
'ing them, but that seems ugly.
In this particular example, the code for the functions isn't that long, so just going ahead and duplicating the code isn't that big a deal. I'm just wondering if an elegant solution exists.