2

Could somebody please direct me to an example on how to retrieve a binData record from MongoDb using C++?
I tried this code, but returns garbage:

char* arrS;

while (dbResult->more())
{
    record = dbResult->next();
    strcpy(arrS, record.getField("s").binData(iLen));
}

"s" is my binData field. Thank you in advance, any suggestions are highly appreciated.

1
  • Does arrS point to any valid memory location prior to strcpy operation ? I believe you know about buffer overflow.
    – Mahesh
    Jul 30, 2012 at 17:32

2 Answers 2

0

The parameter iLen is actually a (second) return value of binData. You can extract the binary contents like this:

int iLen;
const char* p = record["s"].binData(len);
std::string content(p, iLen);
-1

.binData() returns a const char* so it should be returning a pointer to the binary data. You just need to copy that into a buffer, either explicitly allocated or a dynamic one such as a string.

eg.

std::string arrS;
int iLen = 0;
arrS = record.getField("s").binData(iLen);

I'm not sure of the iLen parameter - often this pattern is used to pass in a value of the buffer length and returns the number of bytes copied, but the docs don't mention it.

If so, you need to allocate a buffer:

char arrS[1000];
int iLen = sizeof(arrS);
memcpy(arrS, record.getField("s").binData(iLen));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.