Question

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...

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top