This is some older code - note the open flags on the file. You cannot write the buffer back to the file without closing the fd first
Code:
/******************************
* filemap.c
* provides a memory mapped file to caller
*
*******************************/
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <errno.h>
/* returns the size in bytes of the file */
size_t filesize(int fd)
{
struct stat st;
if(fstat(fd,&st)==(-1))
{
perror("Cannot stat input file");
exit(EXIT_FAILURE);
}
return st.st_size;
}
/***********************
* mapfile maps a file into memory
* arg:
* filename - name of the file to map
* fd - files descriptor - mapfile sets this to an open fd
* filelen - length of file - mapfile sets this to len of file in bytes
* returns:
* pointer to file (byte 0 of file) in memory
*
* any changes made to file in memory are not reflected in the physical file.
***************************/
caddr_t *mapfile(const char *filename, int *fd, size_t *filelen)
{
int filedesc=0;
size_t len=0;
caddr_t *mapptr;
if( (filedesc=open(filename,O_RDONLY))<0)
{
perror("Input file open failure");
exit(EXIT_FAILURE);
}
*fd=filedesc;
len=filesize(filedesc);
*filelen=len;
mapptr=(caddr_t *)mmap(NULL,
len,
PROT_READ|PROT_WRITE,
MAP_PRIVATE,
filedesc,
0);
if(mapptr==MAP_FAILED)
{
perror("Memory mapping of file failed.");
exit(EXIT_FAILURE);
}
return mapptr;
}
/* close files and release memory */
void mapcleanup(caddr_t *ptr, int fd, size_t filelen )
{
if(munmap(ptr,filelen)==(-1))
{
perror("Error releasing memory");
exit(EXIT_FAILURE);
}
while(close(fd)==(-1))
{
if(errno=EINTR)
{
continue;
}
else
{
perror("File I/O Error");
exit(EXIT_FAILURE);
}
}
}