5

In Delphi 7, I open a file with CreateFileMapping then get a pointer by using MapViewOfFile.

How can I expand the memory and add some characters to the memory and have it saved to that file?

I have already opened the file with appropriate modes (fmOpenReadWrite, PAGE_READWRITE), and if I overwrite the characters, it gets saved to the file, but I need to add extra values in the middle of the file.

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
John
  • 1,834
  • 5
  • 32
  • 60

2 Answers2

9

If the file mapping is backed by an actual file and not a block of memory, then you can resize the file in one of two ways:

  1. call CreateFileMapping() with a size that exceeds the current file size. The file will be resized to match the new mapping.

  2. use SetFilePointer() and SetEndOfFile() to resize the file directly, then call CreateFileMapping() with the new size.

Both conditions are described in the documentation for CreateFileMapping().

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
3

You cannot resize file mapping created with CreateFileMapping when it's already created. See earlier discussion on the topic: Windows: Resize shared memory .

Community
  • 1
  • 1
Roman R.
  • 68,205
  • 6
  • 94
  • 158
  • ok, So I assume that I can create a new file from the opened view. One more question, how can i check how long the process address space is, to ensure that I can map the whole file? – John Oct 13 '11 at 10:22
  • It is not exactly the file, it is `file mapping` which is basically shared memory mappable into process address space. Your options are to close/destroy existing file mapping and create a new replacement one, or create an additional file mapping and somehow link the two. There is an option to map the two mappings to result in contiguous address space using `MapViewOfFileEx`, however it is not recommended. – Roman R. Oct 13 '11 at 10:26
  • Well if I have a view to a complete content of the file in memory, I can just use that pointer to write it to a common delphi Stream to save the file with some changes, right? Could you also answer on my sec questions? how to determine the length of the process address space? Thanks – John Oct 13 '11 at 10:36
  • You cannot resize/expand this memory area. You cannot obtain its length directly. You have to keep these values since creation of the file mapping object if you are going to use them later. If you change data in memory you just overwrite it there in regular RAM. – Roman R. Oct 13 '11 at 10:40