C++ 코드로 터미널 크기 구하기

SoByungJun·2023년 2월 10일
0

Linux/C++

목록 보기
1/2
post-thumbnail
#include <stdio.h>
#include <iostream>
#include <sstream>

using namespace std;

constexpr int CMD_MAX_LEN = 256;

string getStringResultFromCommand( const char* cmd ) noexcept
{
    string result;
    char   buffer[CMD_MAX_LEN] = {'\0',};

    // popen : 주어진 cmd 를 shell 로 실행하고 파이프 fd 반환
    FILE* stream = popen( cmd, "r" );
    if( stream ) {
        // popen 및 shell cmd 성공적으로 수행했다면, 결과 출력값을 string 으로 반환
        while( fgets( buffer, CMD_MAX_LEN, stream ) != NULL ) result.append( buffer );
        pclose( stream );
    }
    return result;
}

// if Terminal Size 50(Lines) x 100(Columns) -> 'stty size' return : 50 100
inline void getConsoleSize( int& width, int& height )
{
    // getStringResultFromCommand 이용해서 터미널 사이즈 받은 다음 토큰화
    istringstream iss( getStringResultFromCommand( "stty size" ) );
    string        tokenString;

    getline( iss, tokenString, ' ' );
    height = stoi( tokenString );

    getline( iss, tokenString, ' ' );
    width = stoi( tokenString );
}

int getConsoleWidth()
{
    try         { return stoi( getStringResultFromCommand( "stty size | awk '{print $2}'" ) ); }
    catch (...) { return 0; }
}

int getConsoleHeight()
{
    try         { return stoi( getStringResultFromCommand( "stty size | awk '{print $1}'" ) ); }
    catch (...) { return 0; }
}

int main()
{
    int consoleW, consoleH;
    getConsoleSize( consoleW, consoleH );

    printf("\n");
    printf("[ getConsoleSize() ]\n");
    printf("- Console Width  : %d\n", consoleW);
    printf("- Console Height : %d\n", consoleH);

    printf("\n");
    printf("[ getConsoleWidth() / getConsoleHeight() ]\n");
    printf("- Console Width  : %d\n", getConsoleWidth());
    printf("- Console Height : %d\n", getConsoleHeight());
    printf("\n");

    return 0;
}

profile
좋아서 하는 일

0개의 댓글