Reputation: 85
I have two DWORD. One is a pointer to a section of memory that I have to read and the other is the message length. I need to copy that "buffer" and save it to a file in hexadecimal. In addition I have to save other data. So far I have:
ofstream logFile;
logFile.open("log.txt");
int coutSend = 0;
int countRecv = 0;
void SavePacket(DWORD MemoryPointer, DWORD BufferLength, bool Direction)
{
if (Direction == 0) {
countSend++;
}
else
{
countRecv++;
}
time_t now = time(0);
tm *ltm = localtime(&now);
char * pMemory= reinterpret_cast<char*>(MemoryPointer);
char * msg= new char[BufferLength];
strcpy_s(msg, BufferLength, pMemory);
logFile << ltm->tm_hour << ":" << ltm->tm_min << ":" << ltm->tm_sec << "," << Direction << "," << hex << msg << endl;
}
So if I logFile << pMemory writes the entire message as ascii but I need to write it as hexadecimal.
Upvotes: 0
Views: 685
Reputation: 118350
Besides writing the output in hexadecimal, you have a major memory leak. You're malloc-ing a buffer, that you're not free-ing.
First of all, you are uselessly copying the pointer into the malloced buffer, for no apparent purpose whatsoever. Your original pMemory
pointer will do just as well of a job of writing out the output as the msg
copy. So, the first step is to get rid of allocating msg
and copying the memory, for no useful purpose, and fixing the memory leak that way.
Now, as far as writing hexadecimal, use the std::hex
and std::setw(2)
manipulators, and write out the character buffer one byte at a time, using a loop.
while (bufferLength)
{
logFile << std::hex << std::setw(2) << (int)(unsigned char)*pMemory;
++pMemory;
--bufferLength;
}
Upvotes: 1