C++Builder Programming Forum
C++Builder  |  Delphi  |  FireMonkey  |  C/C++  |  Free Pascal  |  Firebird
볼랜드포럼 BorlandForum
 경고! 게시물 작성자의 사전 허락없는 메일주소 추출행위 절대 금지
C++빌더 포럼
Q & A
FAQ
팁&트릭
강좌/문서
자료실
컴포넌트/라이브러리
메신저 프로젝트
볼랜드포럼 홈
헤드라인 뉴스
IT 뉴스
공지사항
자유게시판
해피 브레이크
공동 프로젝트
구인/구직
회원 장터
건의사항
운영진 게시판
회원 메뉴
북마크
볼랜드포럼 광고 모집

C++빌더 팁&트릭
C++Builder Programming Tip&Tricks
[466] 디버깅을 위한 콘솔 출력입니다. ^^ 중복이지만 그래도 예쁘게 봐주세요.
황경록 [mpbox] 7135 읽음    2005-06-20 16:40
콘솔 출력은 프로그래머라면 누구나 자신만의(결국 똑같지만 ^^;;;) 클래스나 코드를 가지고 있게 마련이죠.
콘솔 출력이 필요하신 분이라면 아무나~

사용방법은 그냥 클래스의 private member 에 TZConOut zout; 선언해 주시고
zout.trace("%s\n", param); 뭐 이런식으로 사용하시면 됩니다.
간단하죠?

2005.07.05

TZConOut -> TZGConout 으로 변경하였습니다.

cpp 파일의 #pragma hdrstop 위에 선언만 하시면 됩니다.

즉...

#include <VCL.h>
#include "unitZGConout.h"

#pragma hdrstop

...

그리고 zout 전역 변수를 선언해 놓았습니다. 그냥 위에 처럼 하시고

zout.trace 를 사용하시면 됩니다.

사용예를 보이면

#ifdef APP_INFO
zout.trace("%s%s\n", APP_INFO, "program started!");
#endif

#ifdef APP_EXCEPTION
zout.trace("%s%s\n", APP_EXCEPTION, e.Message);
#endif

#ifdef APP_NETWORK
zout.trace("%sCommand : %d", APP_NETWORK, iCmd);
#endif

뭐 이런식으로 하시면 됩니다.

소스 압축파일은 새로 올리지 않았습니다. 밑에 붙여넣기한 소스를 참고하시기 바랍니다.




----------------- 헤더 입니다. ------------------------
#ifndef unitZGConoutH
#define unitZGConoutH

#define APP_INFO                    "INFO: "
#define APP_SUCCEEDED               "SUCCEEDED: "
#define APP_FAILED                  "FAILED: "
#define APP_DOUBT                   "DOUBT: "
#define APP_UNEXPECTED              "UNEXPECTED: "
#define APP_ERROR                   "ERROR: "
#define APP_EXCEPTION               "EXCEPTION: "
#define APP_NETWORK                 "NETWORK: "

#define DESC_UNKNOWN_EXCEPTION      "unknown Exception raised."
#define DESC_UNKNOWN_SYSTEM_ERROR   "unknown system error raised."

#include <Classes.hpp>

class TZGConout
{
public:
    TZGConout(void);
    virtual ~TZGConout(void);

private:
    static bool m_bInited;
    static int m_iRefCount;

    HANDLE m_hOut;

private:
    bool m_bShowTime;
public:
    void setShowTime( bool bShowTime );

public:
    static int WINAPI stdCtrlHandler( DWORD fdwCtrlType );
    void setCtrlHandler( PHANDLER_ROUTINE pfnCtrlHandler );

public:
    HANDLE getHandle(void);

    void trace( const char* pMsg, ... );
    void printLastError( DWORD dwError );
    void clear(void);
    void clear( HANDLE hConsole );
};

bool TZGConout::m_bInited = false;
int  TZGConout::m_iRefCount = 0;

static TZGConout zout;

#endif
------------------- 소스 입니다. -----------------------

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#pragma hdrstop

#include "unitZGConout.h"

#pragma package(smart_init)

TZGConout::TZGConout(void)
{
    m_iRefCount++;

    if( m_bInited )
        return ;

    m_bShowTime = false;

    AllocConsole();
    freopen("CONIN$", "rb", stdin);
    freopen("CONOUT$", "wb", stdout);
    freopen("CONOUT$", "wb", stderr);
    setbuf(stderr, 0);

    m_hOut = GetStdHandle( STD_OUTPUT_HANDLE );

    _COORD SBSize;

    SBSize.X = 120; //80;
    SBSize.Y = 3000;
    SetConsoleScreenBufferSize( m_hOut, SBSize );
    SetConsoleActiveScreenBuffer( m_hOut );

    m_bInited = true;
   
    printf("%s %s, %s %s\n", "Application Version :", __DATE__, __TIME__, "Consol ouput initialized.");
}

TZGConout::~TZGConout(void)
{
    m_iRefCount--;

    if( 0 < m_iRefCount )
        return ;

    fclose(stdout);
    fclose(stdin);
    fclose(stderr);

    CloseHandle(m_hOut);
    m_hOut = NULL;

    FreeConsole();

    m_bInited = false;
    m_iRefCount = 0;
}

void TZGConout::setShowTime( bool bShowTime )
{
    m_bShowTime = bShowTime;
}

HANDLE TZGConout::getHandle(void)
{
    return m_hOut;
}

void TZGConout::trace( const char* pMsg, ... )
{
    char cszMsg[MAX_PATH] = { 0x0 };
    va_list va;

    if( pMsg == NULL ) return ;

    try
    {
        if( strlen(pMsg) == 0 ) return ;
        if( strlen(pMsg) > (MAX_PATH - 1) )
        {
            #ifdef APP_ERROR
            printf("%sTrace Buffer Overflow!\n", APP_ERROR);
            #endif

            return ;
        }

        va_start( va, pMsg );
        vsprintf( cszMsg, pMsg, (va_list)va );
        va_end( va );
    }
    catch( const Exception &e )
    {
        #ifdef APP_EXCEPTION
        if( e.Message.Length() > 0 )
            printf("%s%s\n", APP_EXCEPTION, e.Message);
        else
            printf("%s%s\n", APP_EXCEPTION, DESC_UNKNOWN_EXCEPTION);
        #endif

        return ;
    }
    catch( ... )
    {
        #ifdef APP_EXCEPTION
        printf("%s%s\n", APP_EXCEPTION, DESC_UNKNOWN_EXCEPTION);
        #endif
       
        return ;
    }

    if( m_bShowTime )
    {
        printf("%s | %s", Now().FormatString("yyyy-mm-dd hh:nn:ss"), cszMsg);
    }
    else
        printf("%s", cszMsg);
}

void TZGConout::printLastError( DWORD dwError )
{
    LPVOID lpMsgBuf = NULL;

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
        NULL,
        dwError,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
        (LPTSTR) &lpMsgBuf,
        0,
        NULL
    );

    #ifdef APP_ERROR
    if( NULL != lpMsgBuf )
        printf("%s%d> %s", APP_ERROR, dwError, (char*)lpMsgBuf);
    else
        printf("%s%d> Undefined System Error\n", APP_ERROR, dwError);
    #endif

    LocalFree( lpMsgBuf );
}

void TZGConout::clear(void)
{
    system("cls");
}

void TZGConout::clear( HANDLE hConsole )
{
   COORD coordScreen = { 0, 0 }; // home for the cursor
   DWORD cCharsWritten;
   CONSOLE_SCREEN_BUFFER_INFO csbi;
   DWORD dwConSize;

   // Get the number of character cells in the current buffer.

   if( ! GetConsoleScreenBufferInfo(hConsole, &csbi) )
        return ;

   dwConSize = csbi.dwSize.X * csbi.dwSize.Y;

   // Fill the entire screen with blanks.

   if( ! FillConsoleOutputCharacter(hConsole, (TCHAR) ' ',
      dwConSize, coordScreen, &cCharsWritten) )
      return ;

   // Get the current text attribute.

   if( ! GetConsoleScreenBufferInfo(hConsole, &csbi) )
      return ;

   // Set the buffer's attributes accordingly.

   if( ! FillConsoleOutputAttribute(hConsole, csbi.wAttributes,
      dwConSize, coordScreen, &cCharsWritten) )
      return ;

   // Put the cursor at its home coordinates.

   SetConsoleCursorPosition( hConsole, coordScreen );
}

int WINAPI TZGConout::stdCtrlHandler( DWORD fdwCtrlType )
{
    switch( fdwCtrlType )
    {
        case CTRL_C_EVENT: // Handle the CTRL-C signal.
            Beep( 750, 300 );
            system("cls");
            return( TRUE );

        case CTRL_CLOSE_EVENT: // CTRL-CLOSE: confirm that the user wants to exit.
            Beep( 600, 200 );
            Beep( 600, 190 );
            Beep( 600, 180 );
            return FALSE; //  Pass other signals to the next handler.

        //// Pass other signals to the next handler.

        case CTRL_BREAK_EVENT:
            Beep( 900, 200 );
            return FALSE;

        case CTRL_LOGOFF_EVENT:
            Beep( 1000, 200 );
            return FALSE;

        case CTRL_SHUTDOWN_EVENT:
            Beep( 750, 500 );
            return FALSE;

        default:
            return FALSE;
    }
}

void TZGConout::setCtrlHandler( PHANDLER_ROUTINE pfnCtrlHandler )
{
    if( SetConsoleCtrlHandler((PHANDLER_ROUTINE)pfnCtrlHandler, true) )
    {
        printf( "\nThe Control Handler is installed.\n" );
        printf( "\n -- Now try pressing Ctrl+C(Clear) or Ctrl+Break(Exit)," );
        printf( "\n    or try logging off or closing the console...\n" );
    }
    else
        printf( "\nERROR: Could not set control handler");
}
황경록 [mpbox]   2005-06-27 14:10 X
2005.06.27 새로 업데이트 되었습니다.

+ -

관련 글 리스트
466 디버깅을 위한 콘솔 출력입니다. ^^ 중복이지만 그래도 예쁘게 봐주세요. 황경록 7135 2005/06/20
Google
Copyright © 1999-2015, borlandforum.com. All right reserved.