blob: 042dafbd7602f85ad3f6f76b85b28bbf516f70a2 [file] [log] [blame]
Artem Senicheve8837d52020-06-07 11:59:04 +03001// SPDX-License-Identifier: Apache-2.0
2// Copyright (C) 2020 YADRO
3
4#include "zlib_file.hpp"
5
6#include "zlib_exception.hpp"
7
8ZlibFile::ZlibFile(const std::string& fileName)
9{
10 fd = gzopen(fileName.c_str(), "w");
11 if (fd == Z_NULL)
12 {
13 throw ZlibException(ZlibException::create, Z_ERRNO, fd, fileName);
14 }
15 this->fileName = fileName;
16}
17
18ZlibFile::~ZlibFile()
19{
20 if (fd != Z_NULL)
21 {
22 gzclose_w(fd);
23 }
24}
25
26void ZlibFile::close()
27{
28 if (fd != Z_NULL)
29 {
30 const int rc = gzclose_w(fd);
31 if (rc != Z_OK)
32 {
33 throw ZlibException(ZlibException::close, rc, fd, fileName);
34 }
35 fd = Z_NULL;
36 fileName.clear();
37 }
38}
39
40void ZlibFile::write(const tm& timeStamp, const std::string& message) const
41{
42 int rc;
43
44 // Write time stamp
45 rc = gzprintf(fd, "[ %02i:%02i:%02i ] ", timeStamp.tm_hour,
46 timeStamp.tm_min, timeStamp.tm_sec);
47 if (rc <= 0)
48 {
49 throw ZlibException(ZlibException::write, rc, fd, fileName);
50 }
51
52 // Write message
53 const size_t len = message.length();
54 if (len)
55 {
56 rc = gzwrite(fd, message.data(), static_cast<unsigned int>(len));
57 if (rc <= 0)
58 {
59 throw ZlibException(ZlibException::write, rc, fd, fileName);
60 }
61 }
62
63 // Write EOL
64 rc = gzputc(fd, '\n');
65 if (rc <= 0)
66 {
67 throw ZlibException(ZlibException::write, rc, fd, fileName);
68 }
69}