map file in memory

Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: Nov 2007
Posts: 18
Reputation: doublex is an unknown quantity at this point 
Solved Threads: 0
doublex doublex is offline Offline
Newbie Poster

map file in memory

 
0
  #1
Dec 9th, 2007
hi there,
i try to map a file in memory, in linux, using mmap, so that what i write in memory will be written in the file as well.

the piece of code looks like this

  1. fd = open(argv[1], O_RDWR);
  2. if (fd == -1) {
  3. error_message(__FILE__, __LINE__, "'open' failed ");
  4. return 1;
  5. }
  6.  
  7. // find out the size of the file in bytes
  8. // we need the size, because we cannot write past the end of the file
  9. // so, we need to make sure not to write at an offset larger than 'info.st_size'
  10. if (fstat(fd, &info) == -1) {
  11. error_message(__FILE__, __LINE__, "'fstat' failed ");
  12. return 1;
  13. }
  14.  
  15. printf("The file has %ld bytes\n", info.st_size);
  16. if (info.st_size == 0) {
  17. fprintf(stderr, "We cannot map a file with size 0\n");
  18. return 0;
  19. }
  20.  
  21.  
  22. // TODO
  23. mapping = mmap(NULL, info.st_size, PROT_WRITE, MAP_PRIVATE, fd, 0);
  24. if (mapping == MAP_FAILED) {
  25. perror("mmap:");
  26. return -1;
  27. }
  28. else fprintf(stderr, "Successful mapping at the address %p\n", mapping);
  29.  
  30. memcpy(mapping, "hello", 5);
  31.  
  32. if (msync(mapping, info.st_size, MS_SYNC) == -1) {
  33. perror("msync:");
  34. return -1;
  35. }
  36.  
  37. // close the file
  38. if (close(fd) == -1) {
  39. error_message(__FILE__, __LINE__, "'close' failed ");
  40. return 1;
  41. }

i don't realy know how this works, but i think msync should update the file with the contents from memory.

what is wrong with the code?
Reply With Quote Quick reply to this message  
Join Date: Nov 2007
Posts: 18
Reputation: doublex is an unknown quantity at this point 
Solved Threads: 0
doublex doublex is offline Offline
Newbie Poster

Re: map file in memory

 
0
  #2
Dec 9th, 2007
nevermind... i just found that the program was actually working... but the changes i made were not visible unless i closed the file, and opened again. i don't know why this happens. if i change the file in another editor, and save it, i'm announced that the contents were changed outside the program, but if i modify the file using mmap it doesn't say anything
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC