/* mapcat: mmap() a file and copy it to stdout. Useful for reading special files that can be mmapped but not read. Written by Phil Endecott, 2008. I place this code in the public domain; do what you like with it. */ #include #include #include #include #include #include #include #include int main(int argc, char* argv[]) { if (argc!=3) { fputs("Usage: mapcat \n", stderr); exit(1); } const char* fn = argv[1]; char* endptr; size_t length = strtoul(argv[2],&endptr,0); if (*endptr) { fprintf(stderr,"Failed to parse length '%s' at character '%c'\n",argv[2],*endptr); exit(1); } int fd = open(fn,O_RDONLY); if (fd==-1) { perror("open()"); exit(1); } void* addr = mmap(NULL, length, PROT_READ, MAP_SHARED, fd, 0); if (addr==MAP_FAILED) { perror("mmap()"); exit(1); } void* buf = malloc(length); if (!buf) { perror("malloc()"); exit(1); } memcpy(buf,addr,length); int bytes_left=length; void* p = buf; while (bytes_left) { int b = write(1,p,bytes_left); if (b==0) { perror("write()"); exit(1); } p += b; bytes_left -= b; } }