/* * writer.c */ #include #include #include #include #include #include #include #include int main(int argc, char *argv[]) { char *file_data; struct stat sb; int fd; char buf[1]; /* open the file */ if((fd = open("test-file", O_RDWR)) < 0) { perror("open"); exit(1); } /* get file metadata, most especially its size */ if(fstat(fd, &sb) < 0) { perror("fstat"); exit(2); } /* set up the mapping */ file_data = mmap(NULL, sb.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); /* pause */ write(1, "hit enter to write\n", 19); read(0, buf, 1); /* modify the file by messing with the mapped memory */ memcpy(file_data + 8, "MINE", 4); printf("in memory now: \"%s\"\n", file_data); /* pause */ write(1, "hit enter to munmap file\n", 25); read(0, buf, 1); /* clean up after ourselves */ munmap(file_data, sb.st_size); close(fd); }