Thread: write a word to file by using lseek and mmap

  1. #1
    Registered User
    Join Date
    Feb 2005

    write a word to file by using lseek and mmap

    Hi all,

    I have a file "myfile", i want to write a 4 bytes word to a particular place of offset 20 from the start of the file by using mmap. Can i do like this:

    int fd, n;
    unsigned char *mf;
    fd = open("myfile", O_WRONLY);
    n = lseek(fd, 20, 0);
    mf = mmap(0, 40, PROT_WRITE, MAP_SHARED, fd, n);
    strcpy(mf, "care");
    msync(mf, 40, MS_SYNC);
    But i always get segmentation fault.

    Can anyone figure out what is wrong? And how to do it?

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Do some error checking, add a few things like so:
      if ((fd = open("myfile", O_WRONLY)) == -1)
        return 1;
    ... And double check you're using the correct value as the last parameter on mmap().
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. mmap program
    By karthigayan in forum C Programming
    Replies: 1
    Last Post: 04-01-2009, 04:38 AM
  2. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM