Modernes C++ programmieren

Okt 23, 2024

lst-0578-book.cpp

// https://godbolt.org/z/Yh7j1WEGc 
class GzWriteStream {                         // RAII-Wrapper
public:
    gzFile gz_ ;                              // C-Struct aus zlib.h
    explicit GzWriteStream(const string& filename)
        : gz_{gzopen(filename.c_str(),"wb9")} // 'w': write, 'b':binary, '9':level
    {
        if(gz_==NULL) throw std::runtime_error(std::strerror(errno));
    }
    ~GzWriteStream() {
        gzclose(gz_);
    }
    GzWriteStream& operator<<(span<char> &data) {
        write(data);
        return *this;
    }
private:
    void write(span<char> data) {
        auto bytes = std::as_bytes(data); // C++20
        auto res = gzwrite(gz_, bytes.data(), size(bytes));
        if(res==0) throw std::runtime_error("Fehler beim Schreiben");
    }
    GzWriteStream(const GzWriteStream&) = delete;            // keine Kopie
    GzWriteStream& operator=(const GzWriteStream&) = delete; // keine Zuweisung
};