#include #include #include #include #include #include #include /* mmap() is defined in this header */ #include #include #define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) void err_sys(char *fmt, ...) { char buf[1024]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); fprintf(stderr, "%s", buf); va_end(ap); exit(EXIT_FAILURE); } int main (int argc, char *argv[]) { int fdout; char *dst; char buf[1024]; if (argc != 2) err_sys ("usage: %s \n", argv[0]); /* open/create the output file */ if ((fdout = open (argv[1], O_RDWR | O_CREAT | O_TRUNC, FILE_MODE)) < 0) err_sys ("can't create %s for writing", argv[1]); /* go to the location corresponding to the last byte */ if (lseek (fdout, sizeof(buf) - 1, SEEK_SET) == -1) err_sys ("lseek error"); /* write a dummy byte at the last location */ if (write (fdout, "", 1) != 1) err_sys ("write error"); if ((dst = mmap (0, sizeof(buf), PROT_READ | PROT_WRITE, MAP_SHARED, fdout, 0)) == (caddr_t) -1) err_sys ("mmap error for output"); // we do a strcpy from one buffer to another, and file's contents will be updated while ( fgets(buf, sizeof(buf), stdin) ) { strcpy(dst, buf); } return 0; }