"L'implementazione"
- Codice:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "queue.h"
#include "item.h"
struct queue { int head; int tail; int N; int maxN; FILE *s;};
Q queueInit(int maxN) {
Q coda = malloc(sizeof(Q));
char nomefile[15];
sprintf(nomefile, "queue_%p\n", coda);
if ((coda->s = fopen(nomefile, "wb+")) == NULL) {
puts("File could not be opened.");
return(NULL);
}
coda->head = coda->tail = 0;
coda->maxN = maxN;
return coda;
}
int queueIsEmpty(Q coda) {
return coda->N == 0;
}
void queueEnqueue(Q coda, Item item) {
if ( coda->N < coda->maxN ) {
fseek(coda->s, (coda->tail) * sizeof(Item), SEEK_SET);
fwrite(&item, sizeof(Item), 1, coda->s);
coda->tail = (coda->tail + 1)%coda->maxN;
coda->N++;
}
else puts("Not enqueued. Queue overflow.\n");
}
Item queueDequeue(Q coda) {
if ( coda->N > 0 ) {
fseek(coda->s, (coda->head) * sizeof(Item), SEEK_SET);
Item value;
fread(&value, sizeof(Item), 1, coda->s);
coda->head = (coda->head + 1)%coda->maxN;
coda->N--;
return value;
}
else puts("Not dequeued. Queue underflow.\n");
return NULLITEM;
}
"Gli header files"
- Codice:
typedef int Item;
#define NULLITEM -1
#define eq(a, b) ((a) == (b))
- Codice:
#include "item.h"
typedef struct queue *Q;
Q queueInit(int maxN);
int queueIsEmpty(Q);
void queueEnqueue(Q, Item);
Item queueDequeue(Q);
"Un client"
- Codice:
#include <stdio.h>
#include <string.h>
#include "item.h"
#include "queue.h"
void instructions(void);
int main(void) {
Q coda = queueInit(100);
int value;
instructions();
printf("%s", "? ");
char choice;
scanf("%c", &choice);
while (choice != '3') {
switch (choice) {
case '1':
printf("%s", "Enter an integer: ");
scanf("%d", &value);
queueEnqueue(coda, value);
break;
case '2':
if (!queueIsEmpty(coda)) {
printf("The dequeued value is %d.\n", queueDequeue(coda));
}
break;
case '\n':
break;
default:
puts("Invalid choice.\n");
instructions();
break;
}
printf("%s", "? ");
scanf("%c", &choice);
}
puts("End of run.");
}
// display program instructions to user
void instructions(void)
{
puts("Enter choice:\n"
"1 to put a value in the queue\n"
"2 to get a value off the queue\n"
"3 to end program");
}
Da quello che ho capito questo programma dovrebbe creare dei file binari contenenti gli elementi inseriti dal client. Ma a quanto pare non sembra funzionare correttamente, e non essendoci nessun riferimento a questa implementazione nelle lezioni, non riesco a capire il problema e non ho neanche la possibilità di avere qualche delucidazione. E' possibile avere qualche chiarimento? Grazie mille in anticipo!