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),
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),
To me, this means your call to
resize_file()will have no effect if your file is already mapped. You have to unmap it, callresize_file(), and then remap it, which may or may not be what you want.