Increase memory mapping file size

Possible duplicate:
How to dynamically deploy a memory mapped file

hi I have a tree similar to a data structure that is stored in a file with memory mapping in windows. And when I needed to insert a record, I check if the pointer is free near the end of the file. But the real problem is resizing the file.

Windows documentation says that `CreateFileMapping 'will resize the file according to its parameters. So I decided to use it like a roar.

#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 it work. I am a little to blame for this because I just open and reconfigure the file and have not cleared it. Do I need to clean it and do any other operations?

- thanks in advance -

+4
source share
1 answer

The MSDN documentation says two things.

Firstly (in the "Comments" section),

"If the application specifies a size for the file association 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 specifies PAGE_READWRITE or PAGE_EXECUTE_READWRITE ), then the file on disk will grow in accordance with the specified size of the map object If the file is expanded, 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 determined by the file system "

This basically means that your file on disk will be modified when you map it to a memory area larger than the file calling CreateFileMapping() , and fill it with unspecified material.

Secondly (in the "Return Value" section),

"If the object exists before the function is called, the function returns a handle to the existing object ( with its current size, not the specified size ), and GetLastError returns ERROR_ALREADY_EXISTS ."

For me, this means that your call to resize_file() will have no effect if your file is already displayed. You must undo it, call resize_file() , and then reassign it, which may or may not be what you want.

+11
source

All Articles