CS360 Midterm Exam: March 2, 2004. Answer to Question 1

The structure of bsend_to_card follows the bulleted list in the question:

static char buffer[4096];
static int bufbytes = 0;

int bsend_to_card(char *ptr, int nbytes)
{
  /* If nbytes is zero, then flush the card */

  if (nbytes == 0) {            
    if (bufbytes == 0) return 0;
    bufbytes = 0;
    return send_to_card(buffer, bufbytes);
  }

  /* Otherwise, you may need to iterate multiple times */

  while (1) {

    /* If the bytes fit into the buffer, copy them and return */

    if (nbytes + bufbytes <= 4096) {
      memcpy(buffer + bufbytes, ptr, nbytes);
      bufbytes += nbytes;
      return 0;
    }

    /* Otherwise, if the buffer is not emtpy, flush it and try again. */

    if (bufbytes != 0) {
      if (send_to_card(buffer, bufbytes) < 0) return -1;
      bufbytes = 0;

    /* If the buffer is empty, flush 4096 bytes and try again. */

    } else {
      if (send_to_card(ptr, 4096) < 0) return -1;
      ptr += 4096;
      nbytes -= 4096;
      if (nbytes == 0) return 0;
    }
  }
}

You could have used recursion as well, instead of a while loop. If you did so, you needed to make sure you update ptr when you make the recursive call.

Grading: 8 points

The answers here were, simply put, all over the place. I graded you from 0 to 8, based on how much of the concept you communicated to me. Having a few cases, based on nbytes and bufbytes, where you either copied stuff to the buffer or called send_to_card(), got you higher marks. Having the following types of randomness got you low marks: calling write(), fwrite(), strdup(), strlen(), open(), etc. Flagging errors with fprintf() or exit(), etc. Having 0x10000 or the value 1000 in your answer, etc.