본문 바로가기
개발 및 운영/프로그래밍

C++ istream, streambuf 간단 구현 예제

by Joseph.Lee 2019. 7. 19.
#include <iostream>

class input_buf : public std::streambuf
{
public:
    char read_buf_[32];
    int read_pos_;
    int read_limit_;

    input_buf()
    {
        int i;
        for (i = 0; i < 32; i++) {
            if(i < 26)
                read_buf_[i] = 'a' + i;
            else
                read_buf_[i] = 'A' + (i - 26);
        }

        read_pos_ = 0;
        read_limit_ = 32;
    }

    int_type underflow() override
    {
        // 읽을 데이터가 없으면 EOF를 알린다
        int_type ret = traits_type::eof();

        // istream에서 더이상 버퍼에서 읽을게 없으면(setg로 설정한 포인터에 대해 읽기가 끝났으면) 호출됨

        std::cout << "underflow() called" << std::endl;

        if (read_pos_ < read_limit_) {
            // 읽을 데이터가 있으면

            // 읽을 버퍼 주소를 설정해준다.
            // setg(first, next, end)
            this->setg(&read_buf_[read_pos_], &read_buf_[read_pos_], &read_buf_[read_pos_ + 8]);

            // The character at the current position of the controlled input sequence, as a value of type int.
            // 현재 위치의 값을 리턴함
            ret = read_buf_[read_pos_];

            read_pos_ += 8;
        }

        return ret;
    }

};

int main()
{
    input_buf buf;
    std::istream is(&buf);
    int i;


    for (i = 0; i < 100; i++) {
        char c;
        if (!(is >> c))
            break;
        printf("read byte : %c\n", c);
    }

    std::cout << "\nDONE\n";

    return 0;
}
underflow() called
read byte : a
read byte : b
read byte : c
read byte : d
read byte : e
read byte : f
read byte : g
read byte : h
underflow() called
read byte : i
read byte : j
read byte : k
read byte : l
read byte : m
read byte : n
read byte : o
read byte : p
underflow() called
read byte : q
read byte : r
read byte : s
read byte : t
read byte : u
read byte : v
read byte : w
read byte : x
underflow() called
read byte : y
read byte : z
read byte : A
read byte : B
read byte : C
read byte : D
read byte : E
read byte : F
underflow() called

DONE
반응형

댓글