I'm trying to learn how to use mmap; I have managed to read from a file mapped in memory, however when trying to write I constantly get a "segmentation fault". The code (to write) that fails me is the following:
#include <stdlib.h>
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>
int main()
{
FILE* punte;
char* prueba;
punte=fopen("prueba.txt","w");
prueba=(char*)mmap(NULL,sizeof(char)*1,PROT_WRITE,MAP_SHARED,fileno(punte),0);
prueba[0]='A';
munmap(prueba,sizeof(char)*1);
fclose(punte);
return 0;
}
It's code nonsense that only paints the letter 'A' in the text file, but I'm unable to make it work.
Solution (from @eferion):
#include <stdlib.h>
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int file;
char* prueba;
file=open("prueba.txt", O_RDWR); //<-- esto SI funciona
//file=open("prueba.txt", O_WRONLY); //<-- Pero esto no!
lseek(file, 9, SEEK_SET);
write(file, "", 1);
prueba=(char*)mmap(NULL,sizeof(char)*10,PROT_WRITE,MAP_SHARED,file,0);
prueba[0]='A';
munmap(prueba,sizeof(char)*10);
close(file);
return 0;
}