Write to mapped memory file

Posted on 2006-04-05
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.
Question by:trubiat
    LVL 12

    Expert Comment

    What exactly is your question ?

    Author Comment

    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)...
    LVL 12

    Accepted Solution


    Author Comment

    i gave you a B grade because you tried to help but did not solve my question....The link you sent me defines mmap() doesn't show how to write to a file mapped in memory, or read from it....thanks anyways
    LVL 2

    Expert Comment

    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.

    Featured Post

    Threat Intelligence Starter Resources

    Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

    Join & Write a Comment

    This tutorial is posted by Aaron Wojnowski, administrator at  To view more iPhone tutorials, visit This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
    Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode ( They will have you believe that Unicode requires you to use…
    The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
    The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now