安全な文字列のはかり方
文字列の長さを測るのはメモリを書き換えたりしないので安全な関数など新規に要らない気がするが、マイクロソフトは文字列の数を数える関数を新しく書いている。で、そのサンプルプログラムなのだが、あんまし自然なサンプルじゃないなあとか思う。まあ、サンプルなんてみんなそんなものだ。
StringCchLength()
/** strsafe.hの使い方の練習 StringCchLength() 2005/May/18 */ #include <stdio.h> #include <stdlib.h> #include <windows.h> /* using strsafe */ #define STRSAFE_LIB #include <strsafe.h> /* HRESULT StringCchLength( LPCTSTR psz, size_t cchMax, size_t *pcch ); */ int main(int argc, char *argv) { HRESULT result; TCHAR *str = TEXT("Hello World!"); size_t size; result = StringCchLength(str, STRSAFE_MAX_CCH, &size); printf("%s: length = %d\n", str, size); switch(result) { case S_OK: puts("S_OK"); break; case STRSAFE_E_INVALID_PARAMETER: puts("STRSAFE_E_INVALID_PARAMETER"); break; } exit(EXIT_SUCCESS); }