CS360 Midterm Exam: March 2, 2004. Answer to Question 1 |
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.