summaryrefslogtreecommitdiffstats
path: root/source/OSSupport/GZipFile.cpp
blob: cbf6be6c4b7a896ad87582a488d20e47eb5a27a9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

// GZipFile.cpp

// Implements the cGZipFile class representing a RAII wrapper over zlib's GZip file routines

#include "Globals.h"
#include "GZipFile.h"





cGZipFile::cGZipFile(void) :
	m_File(NULL)
{
}





cGZipFile::~cGZipFile()
{
	Close();
}





bool cGZipFile::Open(const AString & a_FileName, eMode a_Mode)
{
	if (m_File != NULL)
	{
		ASSERT(!"A file is already open in this object");
		return false;
	}
	m_File = gzopen(a_FileName.c_str(), (a_Mode == fmRead) ? "r" : "w");
	m_Mode = a_Mode;
	return (m_File != NULL);
}





void cGZipFile::Close(void)
{
	if (m_File != NULL)
	{
		gzclose(m_File);
		m_File = NULL;
	}
}





int cGZipFile::ReadRestOfFile(AString & a_Contents)
{
	if (m_File == NULL)
	{
		ASSERT(!"No file has been opened");
		return -1;
	}
	
	if (m_Mode != fmRead)
	{
		ASSERT(!"Bad file mode, cannot read");
		return -1;
	}
	
	// Since the gzip format doesn't really support getting the uncompressed length, we need to read incrementally. Yuck!
	int NumBytesRead = 0;
	char Buffer[64 KiB];
	while ((NumBytesRead = gzread(m_File, Buffer, sizeof(Buffer))) > 0)
	{
		a_Contents.append(Buffer, NumBytesRead);
	}
	return NumBytesRead;
}





bool cGZipFile::Write(const char * a_Contents, int a_Size)
{
	if (m_File == NULL)
	{
		ASSERT(!"No file has been opened");
		return false;
	}

	if (m_Mode != fmWrite)
	{
		ASSERT(!"Bad file mode, cannot write");
		return false;
	}

	return (gzwrite(m_File, a_Contents, a_Size) != 0);
}