Question

How can I write from a file to shared memory using the Win32 API?

I have this code:

hFile = CreateFile("input.map",
  GENERIC_READ | GENERIC_WRITE,
  FILE_SHARE_READ,
  NULL,
  OPEN_ALWAYS,
  FILE_ATTRIBUTE_NORMAL,
  NULL);

  hMapFile = CreateFileMapping(hFile,
  NULL,
  PAGE_READWRITE,
  0,
  0,
  TEXT("SharedObject"));

  lpMapAddress = (LPTSTR) MapViewOfFile(hMapFile,
  FILE_MAP_ALL_ACCESS,
  0,
  0,
  0);

  ReadFile(
  hFile,
  lpMapAddress,
  75,
  &bytesRead,
  NULL);

  sprintf((char*)lpMapAddress, "<output 1>");

  printf((char*) lpMapAddress);

However, the printf call only returns "< output 1 >" and not the contents of the file.

EDIT: Found the problem. I'm writing to the input file when I call sprintf. But I still don't know why...

Was it helpful?

Solution

Is this the entire code sample? It looks to me like the call to sprintf places a null-terminated string at lpMapAddress, which effectively overwrites whatever you read from the file--at least for the purposes of your printf statement.

If you want to replace the first part of what you read with the string "<output 1>", you could do this after reading the file:

char *tmp = "<output 1>";
strncpy((char*)lpMapAddress, tmp, strlen(tmp));

That copies the text of the string but not its null terminator.

OTHER TIPS

The sprintf stores a NUL after <output 1>, and printf stops at the first NUL.

(Also, it's a bad idea to pass some random file as the format to printf. What if it contained % characters? But that's another issue.)

I'm writing to the input file when I call sprintf. But I still don't know why...

Because that's what MapViewOfFile does. It associates the file's contents with a block of memory. The current contents of the file appear in the memory block, and any changes you make to that memory are written to the file.

I don't think you need to call ReadFile after mapping. Just access the content from the lpMapAddress.

However, using constants for MapViewOfFile makes no benefit from using memory file mapping.

I don't really understand what you are getting at here. It doesn't matter what code you put before; That last line is always going to return the string you placed into the buffer in the previous "sprintf" line. Since that is "<output 1>", yes that's what will be returned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top