Possible Duplicate:
How to dynamically expand a Memory Mapped File
Hi, I have a tree-like data structure stored in a memory-mapped file in Windows and when I needed to insert a record I'm checking if it's free pointer is closer to the file end. But the real problem is about resizing the file.
In the windows documentation, it is said that `CreateFileMapping' will resize the file according to its parameters. So I decided to use it as bellow.
#define SEC_IMAGE_NO_EXECUTE 0x11000000
static void resize_file(wchar_t * file_name,int size)
{
hFile = CreateFile(file_name,GENERIC_READ|GENERIC_WRITE,0,\
NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,\
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
MessageBox(NULL,L"resize_file CreateFile have been failed", szAppName,MB_OK);
exit(0);
}
// open file mapping object //
HANDLE hMap = CreateFileMapping(hFile,NULL,PAGE_EXECUTE_READWRITE|SEC_IMAGE_NO_EXECUTE,0,size,NULL);
// Close files and mapping //
CloseHandle(hMap);
CloseHandle(hFile);
}
Will this work? I have a little guilty about this because I just open and remap the file and didn't flush it. Do I need to flush it and do any other operations too?
The documentation says two things.
Firstly (in the "Remarks" section),
If an application specifies a size for the file mapping object that is larger than the size of the actual named file on disk and if the page protection allows write access (that is, the
flProtect
parameter specifiesPAGE_READWRITE
orPAGE_EXECUTE_READWRITE
), then the file on disk is increased to match the specified size of the file mapping object. If the file is extended, the contents of the file between the old end of the file and the new end of the file are not guaranteed to be zero; the behavior is defined by the file system.
This basically means that your file on disk gets resized when you map it to a memory region larger than the file with the call to CreateFileMapping()
, and fills it up with unspecified stuff.
Secondly (in the "Return Value" section),
If the object exists before the function call, the function returns a handle to the existing object (with its current size, not the specified size), and
GetLastError
returnsERROR_ALREADY_EXISTS
.
To me, this means your call to resize_file()
will have no effect if your file is already mapped. You have to unmap it, call resize_file()
, and then remap it, which may or may not be what you want.