gcc map.c -o map && ./map map.c
File contents:
#include <stdio.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
typedef struct{
char *data;
size_t len;
} mmapbuf;
#define ERR(...) do{fprintf(stderr, __VA_ARGS__); exit(-1);}while(0)
mmapbuf *My_mmap(char *filename){
int fd;
char *ptr;
size_t Mlen;
mmapbuf *ret;
struct stat statbuf;
if(!filename) ERR("No filename given!");
if((fd = open(filename, O_RDONLY)) < 0)
ERR("Can't open %s for reading", filename);
if(fstat (fd, &statbuf) < 0)
ERR("Can't stat %s", filename);
Mlen = statbuf.st_size;
if((ptr = mmap (0, Mlen, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED)
ERR("Mmap error for input");
if(close(fd)) ERR("Can't close mmap'ed file");
ret = malloc(sizeof(mmapbuf));
ret->data = ptr;
ret->len = Mlen;
return ret;
}
void My_munmap(mmapbuf *b){
if(munmap(b->data, b->len))
ERR("Can't munmap");
free(b);
}
int main(int argc, char **argv){
if(argc != 2) return 1;
mmapbuf *readfile = My_mmap(argv[1]);
printf("File contents:\n%s\n", readfile->data);
My_munmap(readfile);
return 0;
}
sprintf (str, "Max:%u,Min:%u", 0x05, 0x00);
sprintf (str, "Max:%hhu,Min:%hhu", 0x05, 0x00);