Article View: borland.public.cppbuilder.nativeapi
Article #383Memory Mapped files
From: 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
Technical Details
Message-ID:
<48093003$1@newsgroups.borland.com>Path:
arc1-ca.pugleaf.net!g2news1.google.com!news3.google.com!feeder.news-service.com!news.isoc.lu!newsgroups.borland.com!not-for-mailShow Full Headers
Complete Article Headers
X-Google-Thread: 10cc67,79f316e1c3e3acf8,start X-Google-Attributes: gid10cc67,domainid0,public,usenet X-Google-Language: ENGLISH,ASCII-7-bit Date: Fri, 18 Apr 2008 16:33:46 -0700 From: Totte Karlsson <tottek@gmail.com> User-Agent: Thunderbird 2.0.0.12 (Windows/20080213) MIME-Version: 1.0 Newsgroups: borland.public.cppbuilder.nativeapi Subject: Memory Mapped files Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit NNTP-Posting-Host: 75.165.79.45 Message-ID: <48093003$1@newsgroups.borland.com> X-Trace: newsgroups.borland.com 1208561667 75.165.79.45 (18 Apr 2008 16:34:27 -0700) Lines: 76 Path: arc1-ca.pugleaf.net!g2news1.google.com!news3.google.com!feeder.news-service.com!news.isoc.lu!newsgroups.borland.com!not-for-mail