Thread View: borland.public.cppbuilder.nativeapi
2 messages
2 total messages
Started by Totte Karlsson
Fri, 18 Apr 2008 23:33
Memory Mapped files
Author: Totte Karlsson
Date: Fri, 18 Apr 2008 23:33
Date: Fri, 18 Apr 2008 23:33
76 lines
2685 bytes
2685 bytes
Hi,
I'm testing out memory mapped files and are having some trouble.
I have a test program where I write bytes to a memory mapped file. Everything
works if I'm using a "view" which is full the size of the file or exactly half
of it. But if I'm setting the view to a quarter or less, the writing of the file
fails, after moving the view first time.
Well, I don't get an error from windows, but inspecting the file reveals that
the writing is not correct.
I have the following code setting up the file
const int ONE_MB = 1048576;
unsigned int fSize = (unsigned int) 1024 * ONE_MB; //in bytes
unsigned int bytesToMap = fSize/2;
CMemoryMappedFile mmFile; //Encapsulate win32 system calls
CFile file(CString("DiskFile"), CFile::modeReadWrite|
CFile::modeCreate|
CFile::shareDenyNone);
if(!mmFile.Open(CString("MapFile"),
(HANDLE) file.m_hFile,
PAGE_READWRITE,
0,
fSize,
bytesToMap))
{
cout<<"Failed opening file";
return 0;
}
The writing to file code is shown below...
unsigned int bytesWrittenInView = 0;
unsigned int totalBytesWritten = 0;
for(unsigned int i = 0; i < fSize/4; i++) //each write is four bytes
{
mmFile.Write((const void*) &i, sizeof(unsigned int));
bytesWrittenInView += sizeof(unsigned int);
totalBytesWritten += sizeof(unsigned int);
if(totalBytesWritten == fSize)
{
cout<<"Finished writing. Wrote "<<totalBytesWritten<<" bytes\n";
break;
}
if(bytesWrittenInView == bytesToMap)
{
if(!mmFile.UnmapViewOfFile())
{
cout<<"Failed to unmap\n";
}
//move the view forward...
if(!mmFile.MapViewOfFile(FILE_MAP_WRITE, 0, bytesWrittenInView, bytesToMap))
{
cout<<"Failed changing the view\n";
break;
}
else
{
cout<<"Changed view..\n";
}
bytesWrittenInView = 0;
}
}
Can't really find whats wrong, any clues?
-totte
Re: Memory Mapped files
Author: Totte Karlsson
Date: Fri, 18 Apr 2008 23:46
Date: Fri, 18 Apr 2008 23:46
27 lines
1768 bytes
1768 bytes
Sorry, I found the problem!
Where I remap the view
if(!mmFile.MapViewOfFile(FILE_MAP_WRITE, 0, bytesWrittenInView, bytesToMap)
I position the view wrongly. Instead of bytesWrittenInView, it should be
totalBytes written. Sorry for that..
Can confirm that Memory mapped files are much faster than regular file I/O..
-tk
Totte Karlsson wrote:
>
> //move the view forward...
> if(!mmFile.MapViewOfFile(FILE_MAP_WRITE, 0,
> bytesWrittenInView, bytesToMap))
> {
> cout<<"Failed changing the view\n";
> break;
> }
> else
> {
> cout<<"Changed view..\n";
> }
>
> bytesWrittenInView = 0;
> }
Thread Navigation
This is a paginated view of messages in the thread with full content displayed inline.
Messages are displayed in chronological order, with the original post highlighted in green.
Use pagination controls to navigate through all messages in large threads.
Back to All Threads