Return to Snippet

Revision: 15992
at July 22, 2009 12:42 by jimfred


Initial Code
// Find the next token in a null-delimited series of strings.
// Example: "a=1234\0b=2345\0c=ABCD\0\0".
// Null bytes ("\0") delimit the strings.
// The whole buffer is terminated by a double null byte ("\0\0").
// strchr is a handy tool to search for next null byte.
// Example usage:
//		for ( LPCSTR pToken = pBuffer; pToken && *pToken; pToken = NextToken(pToken) )
//		{
//			puts( pToken );
//		}
// Use in conjunction with Windows API ::GetPrivateProfileSection
static inline LPCSTR NextToken( LPCSTR pArg )
{
   // find next null with strchr and
   // point to the char beyond that.
   return strchr( pArg, '\0' ) + 1;
}


// Example in the context of GetPrivateProfileSection...

char * pBigString= new char[bufferSize];

// Call GetPrivateProfileSection to populate the buffer.
DWORD dw = GetPrivateProfileSection(
   "MySection",
   pBigString,
   bufferSize,
   "MyIni.ini" );

// Enumerate each token in string.
// The buffer looks like this: "a=1234\0b=2345\0c=ABCD\0\0" 
// Null bytes ("\0") delimit the strings.
// The whole buffer is terminated by a double null byte ("\0\0").
for ( LPCSTR pToken = pBigString; pToken && *pToken; pToken = NextToken(pToken) )
{
   cout << pToken; // Do something with string
}

Initial URL

                                

Initial Description
Some Windows APIs return an array of strings in buffers where each string is NULL delimited and the buffer is double NULL terminated. Using strchr is a convenient way of enumerating. It's easier to read with a 'NextToken' macro/function as shown here.

Initial Title
Enumerate NULL delimited strings that are terminated with a double NULL.

Initial Tags

                                

Initial Language
C++