LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   mmap() error (https://www.linuxquestions.org/questions/programming-9/mmap-error-307737/)

FarAway 03-30-2005 06:52 AM

mmap() error
 
I have a file "b.txt", which is 16 bytes long:

b.txt:
00 12 32 a5 6f ff 11 67 00 00 00 11 fa 90 44 66

I use the following code to change the first 2 bytes of b.txt, and it works.

Code:

int fd, i;
char *mf;
char *buf ;

fd = open("b.txt", O_RDWR);

mf = mmap(0, 2, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

for(i = 0; i < strlen(buf); i++)
    mf[i] = buf[i];

msync(mf, 2, MS_SYNC);

however, if i use
Code:

mf = mmap(0, 2, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 2);
to change the 3rd and 4th (i.e. 32 and a5) of b.txt, segmentation fault occurs.

Can anyone tell me how to map the middle part of a file into memory and do changes to it?

Hivemind 03-30-2005 07:24 AM

In the code you posted the buf doesn't point to anything thus the result of strlen(buf) is undefined.

FarAway 03-30-2005 07:28 AM

sorry i forgot to put in the code buf = "ff"...
but i still got seg fault...

the only way is i mmap the whole file and thus mf point to start of the file.

but if the file is 16MB, is it ok to do it this way?

Hivemind 03-30-2005 07:38 AM

In the code you posted (always post a complete and tested program copied and pasted and not just type something up which you think is similar to the actual code) you don't check if mmap() fails. You should do that and print the error. mmap() doesn't like offsets that are too large (not likely) or offsets that doesn't align with pagesize boundaries (likely).


All times are GMT -5. The time now is 12:29 AM.