Maria Ines Parnisari
Maria Ines Parnisari

Reputation: 17506

Copy stuff to char*

I've got a buffer of type char*, and a string. I want to place inside the buffer the string length + the string.

I wrote the following code to accomplish this but it doesn't work, because the std::cout<<strlen(buffer) prints "1" no matter what string I pass as parameter of the function.

int VariableLengthRecord :: pack (const std::string strToPack)
    {
        int strToPackSize = strToPack.length();
        if (sizeof(strToPackSize) + strToPackSize > maxBytes - nextByte)
            return RES_RECORD_TOO_LONG; // The string is too long

        int start = nextByte;

        // Copy the string length into the buffer
        copyIntToBuffer((buffer+start),strToPackSize);

        // Copy the string into the buffer
        strcpy((buffer+start+sizeof(strToPackSize)),strToPack.c_str());

        // Move the buffer pointer
        nextByte += sizeof(strToPackSize) + strToPackSize;

        // Update buffer size
        bufferSize = nextByte;

        std::cout << "Size of buffer = " << strlen(buffer) << std::endl;
        return RES_OK;
    }


void copyIntToBuffer (char* buffer, int integer)
{
    buffer[0] = integer & 0xff;
    buffer[1] = (integer >> 8) & 0xff;
    buffer[2] = (integer >> 16) & 0xff;
    buffer[3] = (integer >> 24) & 0xff;
}

Upvotes: 0

Views: 132

Answers (3)

Thomas Matthews
Thomas Matthews

Reputation: 57749

In your case, you can't use cout to directly print the buffer, and you can't use strlen either. The problem is that you are storing binary data.

The strlen function will stop at the first 0x00 byte found in the buffer.

The cout will print garbage for non-printable values.

You will need to convert the buffer to an ASCII version of hex values before printing them.

Something like:

for (i = 0; i < BUFFER_SIZE; i ++)
{
    cout << hex << buffer[i];
}
cout << endl;

Upvotes: 1

jeremy
jeremy

Reputation: 4314

strlen is going to walk the string until a null byte (\0) is found. You are attempting to put together a pascal string. If you want to use the built in strlen, you will need to advance the pointer sizeof(string_length_type)

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283893

strlen doesn't work on binary data (the length field is binary). Keep track of the real length, or use 5 + strlen(buffer+4) to measure only the text part.

Or, take advantage of the fact that you stored the length inside the buffer, and read the length from there.

Upvotes: 3

Related Questions