/* circQ.c * Circular queue of characters * Neal Nelson 2010.02.08 * * Take the command line argument and put it in the circular * queue and take it out. * * Then put it in and take it out 5 times to test the wrap-around. * The string is truncated by the size of the circular buffer. */ #include #define MAX_BUF 10 static char qbuf[MAX_BUF]; static int rp, wp; int main(int argc, char **argv) { char mybuf[MAX_BUF+1]; int i,n; if (argc != 2) { printf("Usage: cirQ string\n"); return -1; } /* Print the arc and argv[1] string */ printf("argc: %d\nargc[0]: %s\nargv[1]: %s\n", argc, argv[0], argv[1]); /* Now print the argv[1] string char by char */ for (i = 0; argv[1][i] != 0; i++) { putchar( argv[1][i] ); } printf("\n"); /* initialize read and write buffer pointers */ rp = 0; wp = 0; /* Enqueue the argument string into the circular buffer */ printf("Before enQ: rp: %d, wp: %d\n",rp,wp); n = enQ(argv[1]); printf("After enQ: rp: %d, wp: %d\n",rp,wp); /* Dequeue the circular buffer */ n = deQ(&mybuf); printf("After deQ: rp: %d, wp: %d\n",rp,wp); printf("mybuf: %s\n", mybuf); printf("Done part 1.\n\n"); /* Now enQ and deQ the argument string 5 times * to test the wrap-around */ for (i = 0; i < 5; i++) { printf("Before enQ: rp: %d, wp: %d\n",rp,wp); n = enQ(argv[1]); printf("After enQ: rp: %d, wp: %d\n",rp,wp); n = deQ(&mybuf); printf("After deQ: rp: %d, wp: %d\n",rp,wp); printf("mybuf: %s\n", mybuf); } printf("Done part 2.\n"); } int enQ(char *s) { int i; /* Return number of characters put in queue. * Return 0 if queue full */ printf("rp: %d, wp: %d\n",rp,wp); /* put the argument string into the buffer, no 0 EOS */ for (i = 0; s[i] != 0 && ((wp+1) % MAX_BUF != rp); i++) { qbuf[wp] = s[i]; wp = (wp + 1) % MAX_BUF; printf("rp: %d, wp: %d\n",rp,wp); } return i; } int deQ(char *buf) { int i; /* Fill in the caller's buffer the characters taken from queue. * Return 0 if empty. */ for (i = 0; rp != wp; i++) { buf[i] = qbuf[rp]; rp = (rp + 1) % MAX_BUF; } buf[i] = 0; /* Jam 0 EOS */ return i; }