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;
}
/* fscanf example */
#include <stdio.h>
int main ()
{
char str [80];
float f;
FILE * pFile;
pFile = fopen ("myfile.txt","w+");
fprintf (pFile, "%f %s", 3.1416, "Hello");
rewind (pFile);
fscanf (pFile, "%f", &f);
fscanf (pFile, "%s", str);
fclose (pFile);
printf ("I have read: %f and %s \n",f,str);
return 0;
}
I have read: 3.141600 and Hello