Posted By

jimfred on 07/22/09


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

khouser


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


 / Published in: C++
 

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.

  1. // Find the next token in a null-delimited series of strings.
  2. // Example: "a=1234\0b=2345\0c=ABCD\0\0".
  3. // Null bytes ("\0") delimit the strings.
  4. // The whole buffer is terminated by a double null byte ("\0\0").
  5. // strchr is a handy tool to search for next null byte.
  6. // Example usage:
  7. // for ( LPCSTR pToken = pBuffer; pToken && *pToken; pToken = NextToken(pToken) )
  8. // {
  9. // puts( pToken );
  10. // }
  11. // Use in conjunction with Windows API ::GetPrivateProfileSection
  12. static inline LPCSTR NextToken( LPCSTR pArg )
  13. {
  14. // find next null with strchr and
  15. // point to the char beyond that.
  16. return strchr( pArg, '\0' ) + 1;
  17. }
  18.  
  19.  
  20. // Example in the context of GetPrivateProfileSection...
  21.  
  22. char * pBigString= new char[bufferSize];
  23.  
  24. // Call GetPrivateProfileSection to populate the buffer.
  25. DWORD dw = GetPrivateProfileSection(
  26. "MySection",
  27. pBigString,
  28. bufferSize,
  29. "MyIni.ini" );
  30.  
  31. // Enumerate each token in string.
  32. // The buffer looks like this: "a=1234\0b=2345\0c=ABCD\0\0"
  33. // Null bytes ("\0") delimit the strings.
  34. // The whole buffer is terminated by a double null byte ("\0\0").
  35. for ( LPCSTR pToken = pBigString; pToken && *pToken; pToken = NextToken(pToken) )
  36. {
  37. cout << pToken; // Do something with string
  38. }

Report this snippet  

You need to login to post a comment.