简体   繁体   中英

Convert char buffer to hex and write into a file (VC++)

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM