Pottu
GZFile.hpp
Go to the documentation of this file.
1 
7 #ifndef H_POTTU_GZFILE
8 #define H_POTTU_GZFILE
9 
10 #include <zlib.h>
11 
12 #include <string>
13 #include <stdexcept>
14 #include <cstring>
15 #include <cstdint>
16 
17 
18 namespace pottu {
19 
20 
21  class GZFile {
22  public:
23 
25  GZFile() = default;
26  GZFile( const GZFile &o ) = delete;
27 
28  GZFile( GZFile &&rhs ) {
29  swap( *this, rhs );
30  }
31 
32  friend void swap( GZFile &lhs, GZFile &rhs ) noexcept {
33  using std::swap;
34  swap( lhs._f, rhs._f );
35  }
36 
37  GZFile &operator=(GZFile rhs) noexcept {
38  swap( *this, rhs );
39  return *this;
40  }
41 
42 
44  GZFile( const std::string &filename, const std::string &openmode )
45  {
46  _f = gzopen( filename.c_str(), openmode.c_str() );
47 
48  if( !_f ) {
49  int errnum;
50  std::string errormsg = gzerror( _f, &errnum );
51  throw std::runtime_error( errormsg );
52  }
53 
54  }
55 
58  {
59  if( _f )
60  gzclose( _f );
61  }
62 
63  void open( const std::string &filename, const std::string &openmode ) {
64  if( _f )
65  return;
66  errno = 0;
67  _f = gzopen( filename.c_str(), openmode.c_str() );
68  if( !_f )
69  throw std::runtime_error( std::strerror(errno) );
70  }
71 
72  void close() {
73  if( _f ) {
74  gzclose( _f );
75  _f = nullptr;
76  }
77  }
78 
87  int read( char *buf, unsigned int size ) {
88  if( !_f )
89  throw std::runtime_error( "Cannot read. File is not open." );
90  int ret = gzread( _f, (void *)buf, size );
91  if( ret == -1 ) {
92  int errnum;
93  throw std::runtime_error( gzerror( _f, &errnum ) );
94  }
95  return ret;
96  }
97 
98 
102  void seek( size_t position ) {
103  if( !_f )
104  throw std::runtime_error( "Cannot seek. File is not open." );
105  z_off_t ret = gzseek( _f, position, SEEK_SET );
106  if( ret < 0 )
107  throw std::runtime_error( "gzseek() failed." );
108  }
109 
110 
112  bool isOpen() const noexcept { return _f != nullptr; }
113 
118  bool isZipped() const noexcept { return _f ? gzdirect(_f) != 1 : false; }
119 
120 
121  bool isEof() const noexcept { return _f ? gzeof(_f) : false; }
122 
123  uint64_t getPosition() const noexcept { return _f ? gzoffset(_f) : 0; }
124 
125  gzFile _f{nullptr};
126  };
127 
128 
129 }
130 
131 
132 #endif
Definition: GZFile.hpp:21
int read(char *buf, unsigned int size)
Reads data from the file to a buffer.
Definition: GZFile.hpp:87
bool isOpen() const noexcept
Checks if file is open.
Definition: GZFile.hpp:112
GZFile(const std::string &filename, const std::string &openmode)
Opens the file.
Definition: GZFile.hpp:44
GZFile()=default
Default constructor. Does nothing.
void seek(size_t position)
Seeks the file position.
Definition: GZFile.hpp:102
~GZFile()
Destructor.
Definition: GZFile.hpp:57
bool isZipped() const noexcept
Tells whether the file is zipped.
Definition: GZFile.hpp:118
Definition: mainpage.dox:6