/* inittable.c -- It is called with the command % inittable filename where filename is the name of an existing file with at least NCOUNT person records. It inserts a '\0' at the end of each field of each record. */ #include #include #include #include #include #include #include #define NAMESIZE 26 struct person { // In each fielt I leave space for an extra character char ssn[10]; char name[NAMESIZE]; char grade[3]; // A, A-, B+, B, B-, C+, C, C-, D+, D, D-, F, I }; #define NCOUNT 20 struct moo { struct person a[NCOUNT]; }; int main(int argc, char *argv[]) { struct moo *ptr; int k; int fd; if (argc != 2) { printf("Usage: %s filename\n", argv[0]); exit(0); } if ((fd = open(argv[1], O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO )) < 0){ fprintf(stderr, "Error opening mapped file\n"); exit(1); } if ((ptr = (struct moo *)mmap(0, sizeof(struct moo), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) == (struct moo *)MAP_FAILED) { fprintf(stderr, "Error in mmap\n"); exit(1); } close(fd); for (k=0; k < NCOUNT; ++k) { // insert '\0's in k-th record (ptr->a[k]).ssn[9] = '\0'; (ptr->a[k]).name[NAMESIZE-1] = '\0'; (ptr->a[k]).grade[2] = '\0'; } if (munmap((void *)ptr, sizeof(struct moo)) < 0){ fprintf(stderr, "Error in munmap\n"); exit(1); } return 0; }