Having this:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
int main (void) {
int fd = open("./sometext.txt", O_RDONLY);
struct stat sb;
if(fstat(fd,&sb)) perror("in function fstat");
printf("file size is %ld bytes\n\n",sb.st_size);
char* file_p = mmap(0, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
printf("printing file as an array of chars \n\n");
for(int i =0; i<sb.st_size ; i++){
if(file_p[i]=='a') //cannot do this
file_p[i]='5'; //string/char is read-only, but then how?
printf("%c",file_p[i]);
}
munmap(file_p, sb.st_size);
close(fd);
return 0;
}
As I found from other questions, to change string literal, which is read-only by defaul, I have to either have array storage (char arr[] = "sometext_to_change_in_loop"
) or make another pointer, malloc
need space and then copy the first address of the string that pointer from malloc. But how to change the string "in-line" without doing either of those?
EDIT:
Yes, the main issue was I did not bitwise ORed the int prot
argument in mmap
call. However, how it possible that only that is sufficient?
1) - I do not change int flags
in open
call, so why does it work when open
ed with O_RDONLY
and not with O_RDWD
which makes the same file writeable as well (which I am doing by file_p[i] = '5'
: writting).
2)How can be actually changes saved when in mmap
I have in argument int flags
MAP_PRIVATE
, but I want to save changes, so I should have MAP_SHARED
? according to this tutorial : enter link description here where both - the open flag and the mmap flag were changed as I write. I need to explain this as well.
EDIT2: from the tutorial. It is indeed needed in case of different writing to the file:
for(int i =0; i<sb.st_size ; i++){
file_p[i] = toupper(file_p[i]);
printf("%c",file_p[i]);
}
This will REQUIRED to have set open
flag to O_RDWR
and mmap
flag to MAP_SHARED
. But WHY? Why is one change to file file_p[i]='5'
different in another change file_p[i]=toupper(file_p[i])
? Why does not one change requires to set the two flags (the first case), but the other does require it (second case)? It is confusing for me now.