title: C: code duplication example
body: <p>I'm writing functions that take the checksum of two different things:  one, a file; and two, an archive entry <em>a la</em> the BSD libarchive library.  I borrowed the checksum code from GNU's coreutils.</p>
  
  <p>My code for doing a checksum on a file reads from its source like this:</p>
  
  <pre><code>unsigned char buf[BUFLEN];
  size_t bytes_read;
  FILE *fp;
  ...
  while ((bytes_read = fread (buf, 1, BUFLEN, fp)) &gt; 0) { ... }
  </code></pre>
  
  <p>In my code for reading from an archive entry, the corresponding code looks like</p>
  
  <pre><code>struct archive *ar;
  unsigned char buf[BUFLEN];
  ssize_t bytes_read;
  ...
  while ((bytes_read = archive_read_data(ar, buf, sizeof(buf))) &gt; 0) { ... }
  </code></pre>
  
  <p>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.)</p>
  
  <p>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
  <code>#including</code>'ing them, but that seems ugly.</p>
  
  <p>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.</p>