Thursday, August 05, 2010

mememe1 like strstr

#include

/* ----------------------------------------------------------------------------
* memmem()
* ----------------------------------------------------------------------------
* function
* Like strstr(), but for binary data -- seeks to find 'tofind' in 'source'.
*
* returns
* A pointer to the matching data.
* NULL if not found.
*/
const void* memmem(
const void* source, size_t sourcesize,
const void* tofind, size_t tofindsize
) {
int value;
const void* found;

/* If either 'source' or 'tofind' are missing or blank then we are done */
if (!source || !tofind || !sourcesize || !tofindsize) return source;

value = *(const unsigned char*)tofind;

/* While we can find potential matches */
while ((found = memchr( source, value, sourcesize )))
{
/* Keep track of what amount remains of the source */
sourcesize -= (const unsigned char*)found - (const unsigned char*)source;

/* If there isn't enough of the source left to match, then return 'not found' */
if (sourcesize < tofindsize) return NULL;

/* Did we find an exact match? */
if (memcmp( found, tofind, tofindsize ) == 0) return found;

/* Ready to find the next potential match */
source = (const unsigned char*)found + 1;
sourcesize--;
}

/* No match found */
return NULL;
}

參考來源:

"Since you are working with binary data, you should avoid using string functions. Unfortunately, there is no equivalent of strstr() for binary memory, but it is easy enough to construct one:"
- Checking for null characters in the midd... - C++ Forums (在「Google 網頁註解」中檢視)

No comments: