-1

I'm trying to write a string to a mapped file with c and visual studio.

    ( pFile = (char *) MapViewOfFile(hMMap,FILE_MAP_ALL_ACCESS,0,0,0))

    start = pFile;

    while(pFile < start + 750){
    *(pFile++) = ' ';
    *(pFile++) = 'D';
    *(pFile++) = 'N';
    *(pFile++) = 'C';
    *(pFile++) = 'L';
    *(pFile++) = 'D';
    *(pFile++) = ' ';
    if(!((pFile - start) % 50))
        *(pFile++) = 10;
    else
        *(pFile++) = ',';
}

If i write something like this i can write fine. but i want to write a string this file. How can i do? I have tried

  sprintf(toFile, "A message of %3d bytes is received and decrypted.\n", strlen(message));
  WriteFile(pFile,toFile,strlen(toFile),&bytesWritten,NULL);

this allready...

Deanna
  • 23,876
  • 7
  • 71
  • 156
Ömer Faruk AK
  • 2,409
  • 5
  • 26
  • 47
  • What happened when you tried the second snippet of code? Did you call [`GetLastError`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms679360.aspx) to see what went wrong? – Cody Gray - on strike Dec 17 '11 at 11:44
  • There is no error but it writes to file only a character... – Ömer Faruk AK Dec 17 '11 at 11:48
  • 2
    You just want to write some memory. Use `memcpy` for that. `WriteFile` is completely wrong. Use that when you have a file handle. With a memory mapped file you have a pointer to memory. If you wanted to use `WriteFile` you would just use `CreateFile` and not bother with memory mapping. Perhaps that's really what you need to be doing. – David Heffernan Dec 17 '11 at 16:16

1 Answers1

2

WriteFile() expects an opened HANDLE to a file, not a pointer to a memory address. Just write your new data directly to the contents of the memory being pointed at. You can use C library string functions for that, eg:

char *start = (char *) MapViewOfFile(hMMap,FILE_MAP_ALL_ACCESS,0,0,0);

char *pFile = start; 
while (pFile < (start + 750))
{ 
  strcpy(pFile, " DNCLD ");
  pFile += 7;
  *(pFile++) = (((pFile - start) % 50) == 0) ? '\n' : ','; 
} 
...
sprintf(pFile, "A message of %3d bytes is received and decrypted.\n", strlen(message));     
...
UnmapViewOfFile(start);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770