We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you a podcast all about Citrix Workspace, moving to the cloud, and analytics & intelligence. Episode 2 coming soon!Listen Now


Write to mapped memory file

trubiat asked
Medium Priority
Last Modified: 2010-08-05
I have the following code to create a file, and then map it into memory...I want to write to it and then read from it....

fd = open(argv[2], O_RDWR|O_CREAT, S_IRWXU);
if (fd < 0 )
    f_error("open1() error");
buffer = mmap(0, (size_t)MAX_BUF_SIZE, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, 0);
if (buffer == MAP_FAILED)
    f_error("mmap1() error");

Thanks for your help.
Watch Question

What exactly is your question ?


i want to know how to write to the file which in mapped into the memory, how to read from it, and how to empty it (if I write something, then how do I make the file empty)...

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts


i gave you a B grade because you tried to help but did not solve my question....The link you sent me defines mmap()....it doesn't show how to write to a file mapped in memory, or read from it....thanks anyways
when you call mmap() then the file contents are copied to memory and a character pointer is returned to that data. In your code "buffer" will receive pointer to data area. simply writting
   buffer[0] = 'a';   // will write character 'a' to the first location of file.
if you do
   strcpy(buffer,"test"); // will write the string "test" to the file
same way to read it just

char ch = buffer[0]
char temp[10]
will copy first 10 char of file to temp

how to empty it?? I am not sure but if you write EOF to the first location of file it may empty the file. I will check and confirm this.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.