• C

Write to mapped memory file

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.
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

What exactly is your question ?
trubiatAuthor Commented:
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)...

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
trubiatAuthor Commented:
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.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.