_SNPRINTF_DLLIMPORT int __cdecl vsntprintf( _TCHAR *buffer, size_t count, const _TCHAR *format, va_list list ) { int retval; /* First of all call the existing non POSIX standard function assuming the buffer size will be large enough */ retval = _vsntprintf( buffer, count, format, list ); if ( retval < 0 ) { /* If the buffer wasn't large enough ensure that the buffer will be zero terminated */ _TCHAR *last = GetLastBufferChar( buffer, count ); if (last ) *last = 0; /* Retrieve the count of characters that would have been written if the buffer were large enough */ retval = _vsctprintf( format, list ); } else if ( (size_t)retval == count && count ) { /* If the buffer was large enough but not large enough for the trailing zero make the buffer zero terminated */ _TCHAR *last = GetLastBufferChar( buffer, count ); if (last ) *last = 0; } return retval; }
/** dropt_vsnprintf * * vsnprintf wrapper to provide ISO C99-compliant behavior. * * PARAMETERS: * OUT s : The destination buffer. May be NULL if n is 0. * If non-NULL, always NUL-terminated. * IN n : The size of the destination buffer, measured in * dropt_char-s. * IN format : printf-style format specifier. Must not be NULL. * IN args : Arguments to insert into the formatted string. * * RETURNS: * The number of characters that would be written to the destination * buffer if it's sufficiently large, excluding the NUL-terminator. * Returns -1 on error. */ int dropt_vsnprintf(dropt_char* s, size_t n, const dropt_char* format, va_list args) { #if __STDC_VERSION__ >= 199901L || __GNUC__ /* ISO C99-compliant. * * As far as I can tell, gcc's implementation of vsnprintf has always * matched the behavior required by the C99 standard (which is to * return the necessary buffer size). * * Note that this won't work with wchar_t because there is no true, * standard wchar_t equivalent of snprintf. swprintf comes close but * doesn't return the necessary buffer size (and the standard does not * provide a guaranteed way to test if truncation occurred), and its * format string can't be used interchangeably with snprintf. * * It's simpler not to support wchar_t on non-Windows platforms. */ assert(format != NULL); return vsnprintf(s, n, format, args); #elif defined __BORLANDC__ /* Borland's compiler neglects to NUL-terminate. */ int ret; assert(format != NULL); ret = vsnprintf(s, n, format, args); if (n != 0) { s[n - 1] = DROPT_TEXT_LITERAL('\0'); } return ret; #elif defined _MSC_VER /* _vsntprintf and _vsnprintf_s on Windows don't have C99 semantics; * they return -1 if truncation occurs. */ va_list argsCopy; int ret; assert(format != NULL); va_copy(argsCopy, args); ret = _vsctprintf(format, argsCopy); va_end(argsCopy); if (n != 0) { assert(s != NULL); #if _MSC_VER >= 1400 (void) _vsntprintf_s(s, n, _TRUNCATE, format, args); #else /* This version doesn't necessarily NUL-terminate. Sigh. */ (void) _vsnprintf(s, n, format, args); s[n - 1] = DROPT_TEXT_LITERAL('\0'); #endif } return ret; #else #error Unsupported platform. dropt_vsnprintf unimplemented. return -1; #endif }
void DriverLog::WriteLine(LPCTSTR message, ...) { if (!Active() || message == 0) return; m_cs.Enter(); static TCHAR lineStart[512]; int lineStartSize = _stprintf_s(lineStart, 512, _T("[%4d][%6d]"), ::GetCurrentThreadId(), ::GetTickCount() - startTick); WriteFileLog(lineStart, lineStartSize); va_list args; va_start( args, message ); int characters = _vsctprintf(message, args); if (characters != -1) { DynamicArray<TCHAR> buffer(characters + 5); if(-1 != _vstprintf_s(buffer, characters + 5, message, args)) { WritePipeLog(buffer, characters); buffer[characters] = _T('\r'); buffer[characters + 1] = _T('\n'); WriteFileLog(buffer, characters + 2); } } m_cs.Leave(); }
MapilVoid GLSprite::DrawString( SharedPointer < GraphicsFont > pFont, const MapilTChar* pStr, const Matrix4x4 < MapilFloat32 >& mat ) { if( !pStr ){ return; } #if defined ( API_WIN32API ) glMatrixMode( GL_MODELVIEW ); glPushMatrix(); glLoadMatrixf( mat.m_Elm1 ); ::HDC hdc = wglGetCurrentDC(); // Build string to be displayed. MapilTChar str[ 4096 ]; va_list vl; MapilInt32 len; va_start( vl, pStr ); len = _vsctprintf( pStr, vl ) + 1; if( len > sizeof( str ) ){ return; } _vstprintf( str, pStr, vl ); va_end( vl ); len = _tcslen( str ); SelectObject( hdc, reinterpret_cast < HFONT > ( pFont->Get() ) ); MapilInt32 list = glGenLists( len ); for( MapilInt32 i = 0; i < len; i++ ){ wglUseFontBitmaps( hdc, str[ i ], 1, list + i ); } //glDisable( GL_LIGHTING ); //glColor4f( colR, colG, colB, 1.0f ); glColor4f( 1.0f, 0.0f, 0.0f, 1.0f ); //glRasterPos2i( vPos.m_X, vPos.m_Y ); glRasterPos2i( 0, 0 ); for( MapilInt32 i = 0; i < len; i++ ){ glCallList( list + i ); } //glEnable( GL_LIGHTING ); glDeleteLists( list, len ); glPopMatrix(); #endif // API_WIN32API }
Exception::Exception(LPCTSTR fmt, ...) { va_list args; va_start(args, fmt); int len = _vsctprintf(fmt, args) + 1; if(len > 0) { _vstprintf_s(m_msg.GetBufferSetLength(len), len, fmt, args); } va_end(args); }
void Trace( LPCTSTR format, ... ) { va_list args; va_start( args, format ); std::vector<TCHAR> buffer( _vsctprintf( format, args ) + 1 ); _vstprintf( &buffer[0], format, args ); ::OutputDebugString( &buffer[0] ); }
void LogWriter::vprintLog(int logLevel, const TCHAR *fmt, va_list argList) { if (m_logger != 0) { // Format the original string. int count = _vsctprintf(fmt, argList); std::vector<TCHAR> formattedString(count + 1); _vstprintf(&formattedString.front(), fmt, argList); m_logger->print(logLevel, &formattedString.front()); } }
void Stream::ThrowError(LPCTSTR fmt, ...) { va_list args; va_start(args, fmt); int len = _vsctprintf(fmt, args) + 1; CString str; if(len > 0) _vstprintf_s(str.GetBufferSetLength(len), len, fmt, args); va_end(args); throw Exception(_T("Error (Ln %d Col %d): %s"), m_line + 1, m_col + 1, str); }
/*! */ _tstring strutils::format(LPCTSTR fmt, ...) { va_list args; va_start(args, fmt); _tstring resstr; resstr.resize(_vsctprintf(fmt, args) + 1); _vstprintf_s(&resstr[0], resstr.size(), fmt, args); va_end(args); return resstr; }
MapilVoid GLSprite::DrawString( SharedPointer < GraphicsFont > pFont, const MapilTChar* pStr, ImageTransformationMethod method, const Vector2 < MapilFloat32 >& v, MapilUInt32 color ) { if( !pStr ){ return; } #if defined ( API_WIN32API ) ::HDC hdc = wglGetCurrentDC(); // Build string to be displayed. MapilTChar str[ 4096 ]; va_list vl; MapilInt32 len; va_start( vl, pStr ); len = _vsctprintf( pStr, vl ) + 1; if( len > sizeof( str ) ){ return; } _vstprintf( str, pStr, vl ); va_end( vl ); len = _tcslen( str ); SelectObject( hdc, reinterpret_cast < HFONT > ( pFont->Get() ) ); MapilInt32 list = glGenLists( len ); for( MapilInt32 i = 0; i < len; i++ ){ wglUseFontBitmaps( hdc, str[ i ], 1, list + i ); } //glDisable( GL_LIGHTING ); glColor4i( ( color >> 16 ) & 0xFF , ( color >> 8 ) & 0xFF, color & 0xFF, ( color >> 24 ) & 0xFF ); //glColor4f( 1.0f, 0.0f, 0.0f, 1.0f ); glRasterPos2f( v.m_X, v.m_Y ); for( MapilInt32 i = 0; i < len; i++ ){ glCallList( list + i ); } //glEnable( GL_LIGHTING ); glDeleteLists( list, len ); #endif // API_WIN32API }
int CHgzComboBox::SetWindowsTextFormat( const TCHAR * szFormat, ... ) { va_list arglist; va_start(arglist, szFormat); int len = _vsctprintf(szFormat, arglist)+1; TCHAR *buf = new TCHAR[len]; //TCHAR *buf = (TCHAR *)_alloca((_vsctprintf(szFormat, arglist)+1)*sizeof(TCHAR)); // 动态分配栈内存,无需手动释放。 _vstprintf(buf, szFormat, arglist); SetWindowText(buf); delete [] buf; return len-1; }
/************************************************************************* throw a exception *************************************************************************/ void Util::throwException(const char* szFmt, ...) { va_list argList; va_start(argList, szFmt); unsigned int nSize = _vsctprintf(szFmt, argList); std::string strMessage; strMessage.assign(nSize+1, _T(' ')); _vstprintf((LPTSTR)&(strMessage[0]), szFmt, argList); va_end(argList); throw std::exception(strMessage.c_str()); }
// 抛出字符串形式异常 VOID tThrowStringException(LPCTSTR szFmt, ...) { va_list argList; va_start(argList, szFmt); UINT nSize = _vsctprintf(szFmt, argList); STRING strMessage; strMessage.assign(nSize+1, _T(' ')); _vstprintf((LPTSTR)&(strMessage[0]), szFmt, argList); va_end(argList); throw std::exception(strMessage.c_str()); }
void LOG(LPCTSTR fmt, ...) { va_list args; va_start(args, fmt); if(TCHAR* buff = new TCHAR[_vsctprintf(fmt, args) + 1]) { _vstprintf(buff, fmt, args); if(FILE* f = _tfopen(LOG_FILE, _T("at"))) { fseek(f, 0, 2); _ftprintf(f, _T("%s\n"), buff); fclose(f); } delete [] buff; } va_end(args); }
// Debugging void DebugMsg(const TCHAR * pwszFormat,...) { TCHAR buf[1024] = {'\0'}; va_list arglist; va_start(arglist, pwszFormat); int nBufSize = _vsctprintf(pwszFormat,arglist) + 1; if (nBufSize) { std::auto_ptr<TCHAR> Buffer(new TCHAR[nBufSize]); TCHAR * pBuffer = Buffer.get(); _vstprintf_s(pBuffer,nBufSize,pwszFormat,arglist); va_end(arglist); OutputDebugString(pBuffer); } }
/** * Sorta kinda like StringCchVPrintf somewhat not really. Caller responsible * for cleanup. */ STATIC LPTSTR StringCchVAPrintf(LPCTSTR lpMessage, va_list lpArgs) { TCHAR *lpResult; SIZE_T szDisplayBuf; // Check the resulting size of the buffer. szDisplayBuf = (SIZE_T)_vsctprintf(lpMessage, lpArgs) + 1; // Allocate our buffer. lpResult = (TCHAR*)calloc(szDisplayBuf, sizeof(TCHAR)); assert(lpResult != NULL); // Finally, fill in the message. _vsntprintf(lpResult, szDisplayBuf, lpMessage, lpArgs); return lpResult; }
void _OutputDebugString(const TCHAR *format, ...) { va_list params; va_start(params, format); int iResult; TCHAR *buff; int length = _vsctprintf(format, params); buff = new TCHAR [length + 1]; if (buff != NULL) { iResult = _vstprintf_s(buff, length + 1, format, params); buff[length] = _T('\0'); OutputDebugString(buff); delete[] buff; } va_end(params); }
void GC_TRACE(LPCTSTR lpstrTrace,...) { va_list args; int len; LPTSTR buffer; va_start( args, lpstrTrace ); len = _vsctprintf( lpstrTrace, args ) // _vscprintf doesn't count + 1; // terminating '\0' buffer = (LPTSTR)malloc( len * sizeof(LPTSTR) ); _vstprintf( buffer, lpstrTrace, args ); ::OutputDebugStringA(buffer); //errLog("d:\\zzy.log",COleDateTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S").GetBuffer()); //errLogLn("d:\\zzy.log",buffer); free(buffer); return; }
void _OutputDebugString(const TCHAR *format, ...) { va_list params; va_start(params, format); try{ int length = _vsctprintf(format, params); if( length >= 0 ){ vector<TCHAR> buff(length + 1); _vstprintf_s(&buff.front(), buff.size(), format, params); OutputDebugString(&buff.front()); } }catch(...){ va_end(params); throw; } va_end(params); }
TString StrFmt( const TCHAR* format, ... ) { TString result; TCHAR* buffer; int sz; va_list args; va_start( args, format ); sz = _vsctprintf( format, args ) + 1; buffer = new TCHAR[sz]; _vsntprintf_s( buffer, sz, _TRUNCATE, format, args ); result = buffer; delete [] buffer; va_end( args ); return result; }
/** * Log an event * @param LogType the type of the event been logged * @param const MYODD_CHAR* the unformatted buffer. * @param va_list the list of arguments we will add to the buffer. * @return */ void LogEvent::Log(LogType uiType, const MYODD_CHAR* pszLine, va_list argp) { ASSERT(pszLine != NULL); MYODD_CHAR* buffer = NULL; int len = _vsctprintf(pszLine, argp); if (len >0) { // _vscprintf doesn't count + 1; terminating '\0' ++len; buffer = new MYODD_CHAR[len]; _vsntprintf_s(buffer, len, len, pszLine, argp); } Log(uiType, buffer); if (NULL != buffer) { delete[] buffer; } }
void oem_vprint(LPCTSTR lpszFormat,va_list args){ LPTSTR lpszBuffer; LPSTR lpOEMBuffer; int len,size; // len = _vsctprintf(lpszFormat,args); size = (len + 1) * sizeof(_TCHAR); lpszBuffer = (LPTSTR)malloc(size); lpOEMBuffer = (LPSTR)malloc(len + 1); _vstprintf_s(lpszBuffer,len + 1,lpszFormat,args); #if defined(_UNICODE) sprintf_s(lpOEMBuffer,len + 1,"%ws",lpszBuffer); ::CharToOemA(lpOEMBuffer,lpOEMBuffer); #else ::CharToOemBuff(lpszBuffer,lpOEMBuffer,len); #endif printf_s("%.*s",len,lpOEMBuffer); free(lpOEMBuffer); free(lpszBuffer); }
void Log::vprint(int logLevel, const TCHAR *fmt, va_list argList) { Log *instance = getInstance(); if (instance == 0) { return; } StringStorage timeString(_T("[Temporary unavaliable]")); SYSTEMTIME st; GetLocalTime(&st); timeString.format(_T("%.4d-%.2d-%.2d %.2d:%.2d:%.2d"), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); const TCHAR logLevelSignature[] = _T("@!*+-: xxxxxx"); TCHAR sig = logLevelSignature[logLevel & 0x0F]; int count = _vsctprintf(fmt, argList); TCHAR *formattedString = new TCHAR[count + 1]; _vstprintf(formattedString, fmt, argList); StringStorage message; message.format(_T("[%4d] %s %c %s"), GetCurrentThreadId(), timeString.getString(), sig, formattedString); const TCHAR badCharacters[] = {13, 10, 0}; message.removeChars(badCharacters, sizeof(badCharacters) / sizeof(TCHAR)); delete[] formattedString; const TCHAR endLine[3] = {13, 10, 0}; message.appendString(endLine); instance->flushLine(logLevel, message.getString()); }
// 결과값 출력 함수 void Output(USHORT Color, LPTSTR format, ... ) { va_list args; // typedef char * va_list; int len; DWORD cb; LPTSTR buffer; // typedef LPWSTR PTSTR, LPTSTR; va_start(args, format); /* #define va_start _crt_va_start http://psychoria.tistory.com/entry/%EA%B0%80%EB%B3%80-%EC%9D%B8%EC%9E%90Variable-Arguments-%EB%82%B4%EB%B6%80-%EA%B5%AC%EC%A1%B0 가변 인자 함수는 printf 같이 인자의 형식이나 수가 정해지지 않은 형식의 함수다. 가변 인자 매크로는 stdarg.h에 정의되어 있다. #define _crt_va_start(ap,v) ( ap = (va_list)_ADDRESSOF(v) + _INTSIZEOF(v) ) ap와 v를 전달 받아서 v의 주소에 _INTSIZEOF(v)를 통해서 나온 값을 더해서 ap에 대입합니다. ap는 va_list로 받으며 va_list는 실제로는 단지 char*입니다. 즉, v의 주소에 _INTSIZEOF(v)를 더해준 주소를 char*로 된 포인터에 넣어주는 것입니다. //va_start : va_list로 만들어진 포인터에게 가변 인자 중 첫번째 인자의 주소를 가르쳐줌 //va_start(va_list로 만든 포인터, 마지막 고정 인수) Error : Only Win32 target supported! */ len = _vsctprintf(format, args) + sizeof(TCHAR); // _vsctprintf : 조합될 문자열의 길이 확인, // 문자열의 길이가 크면 동적으로 메모리 확보하여 printf buffer = new TCHAR[len * sizeof(TCHAR)]; // 동적 메모리 생성 - 버퍼 if (!buffer) { return; } _vstprintf_s(buffer, len, format, args); if (g_hFile != INVALID_HANDLE_VALUE) { // #define INVALID_HANDLE_VALUE ((HANDLE)(LONG_PTR)-1) #ifdef _UNICODE LPSTR str = new CHAR[len + 1]; if (str) { memset(str, 0, len + 1); /* *** memset Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char). str를 0으로 len+1개를 채움 void * memset ( void * ptr, int value, size_t num ); ptr : Pointer to the block of memory to fill. value : Value to be set. The value is passed as an int but the function fills the block of memory using the unsigned char conversion of this value. num : Number of bytes to be set to the value. size_t is an unsigned integral type. void * __cdecl memset(_Out_opt_bytecapcount_(_Size) void * _Dst, _In_ int _Val, _In_ size_t _Size); */ WideCharToMultiByte(CP_ACP, 0, buffer, -1, str, len, NULL, NULL); /* *** WideCharToMultiByte WINBASEAPI int WINAPI WideCharToMultiByte( __in UINT CodePage, // Code page to use in performing the conversion. // This parameter can be set to the value of any code page // that is installed or available in the operating system. // CP_ACP : The system default Windows ANSI code page. // Code Page Default Values : 0 __in DWORD dwFlags, __in_ecount(cchWideChar) LPCWSTR lpWideCharStr, __in int cchWideChar, __out_bcount_opt(cbMultiByte) __transfer(lpWideCharStr) LPSTR lpMultiByteStr, __in int cbMultiByte, __in_opt LPCSTR lpDefaultChar, __out_opt LPBOOL lpUsedDefaultChar); */ WriteFile(g_hFile, str, strlen(str), &cb, NULL); /* *** WriteFile Writes data to the specified file or input/output (I/O) device. WINBASEAPI BOOL WINAPI WriteFile( __in HANDLE hFile, __in_bcount_opt(nNumberOfBytesToWrite) LPCVOID lpBuffer, __in DWORD nNumberOfBytesToWrite, __out_opt LPDWORD lpNumberOfBytesWritten, __inout_opt LPOVERLAPPED lpOverlapped ); */ delete[] str; } #else WriteFile(g_hFile, buffer, strlen(buffer), &cb, NULL); #endif } HANDLE Handle = GetStdHandle(STD_OUTPUT_HANDLE); /* *** GetStdHandle Retrieves a handle to the specified standard device (standard input, standard output, or standard error). 표준입출력 및 오류핸들을 리턴 콘솔에서 stdout, stdin, stderr 의 핸들을 가져오는 함수 WINBASEAPI HANDLE WINAPI GetStdHandle( __in DWORD nStdHandle ); //STD_INPUT_HANDLE : 표준 입력 핸들 //STD_OUTPUT_HANDLE : 표준 출력 핸들 //STD_ERROR_HANDLE : 표준 오류 핸들 #define STD_OUTPUT_HANDLE ((DWORD)-11) */ if (Color) { SetConsoleTextAttribute( Handle, Color | FOREGROUND_INTENSITY); // #define FOREGROUND_INTENSITY 0x0008 // text color is intensified. /* *** SetConsoleTextAttribute WINBASEAPI BOOL WINAPI SetConsoleTextAttribute( __in HANDLE hConsoleOutput, __in WORD wAttributes ); */ } _tprintf(buffer); SetConsoleTextAttribute(Handle, FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED); delete[] buffer; }