zlib というのは、ファイルを圧縮、伸張するフリーのライブラリ。ZIP や GZIP などに使われてるので有名よね。

使い方

圧縮

  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
/**
 * データを圧縮.
 */
int
compress(
		unsigned char *src,
		unsigned long srcSize,
		unsigned char *dest,
		unsigned long destMaxSize,
		unsigned long *destSize)
{
	z_stream z;
 
	// メモリ管理はZLIBに任せる
	z.zalloc = Z_NULL;
	z.zfree = Z_NULL;
	z.opaque = Z_NULL;
 
	z.next_in = Z_NULL;
	z.avail_in = 0;
 
	int status = Z_OK;
 
	status = deflateInit(&z, Z_DEFAULT_COMPRESSION);
	if (status != Z_OK) {
		debugs_format(99, 5, "deflateInit: %s\n", (z.msg) ? z.msg : "???");
		return status;
	}
 
	// 入力データを設定
	z.next_in = src;
	z.avail_in = srcSize;
 
	// 出力先を設定
	z.next_out = dest;
	z.avail_out = destMaxSize;
 
	// 圧縮
	//status = deflate(&z, Z_NO_FLUSH);
	status = deflate(&z, Z_FINISH);
	// 成功ではない、またはデータの最後まで読み取れていない場合は失敗
	if (status != Z_OK && status != Z_STREAM_END) {
		debugs_format(99, 5, "deflate: %s\n", (z.msg) ? z.msg : "???");
		return status;
	}
 
	status = deflateEnd(&z);
	if (status != Z_OK) {
		debugs_format(99, 5, "deflateEnd: %s\n", (z.msg) ? z.msg : "???");
		return status;
	}
 
	// 出力サイズを設定
	*destSize = z.total_out;
 
	return 0;
}

伸長

  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
/**
 * 圧縮されているデータを伸長.
 */
int
decompress(
		unsigned char *src,
		unsigned long srcSize,
		unsigned char *dest,
		unsigned long destMaxSize,
		unsigned long *destSize)
{
	z_stream z;
 
	int status = Z_OK;
 
	// メモリ管理はZLIBに任せる
	z.zalloc = Z_NULL;
	z.zfree = Z_NULL;
	z.opaque = Z_NULL;
 
	z.next_in = Z_NULL;
	z.avail_in = 0;
 
	status = inflateInit2(&z, MAX_WBITS + 32);
	if (status != Z_OK) {
		debugs_format(99, 5, "inflateInit: %s\n", (z.msg) ? z.msg : "???");
		return status;
	}
 
	// 入力データを設定
	z.next_in = src;
	z.avail_in = srcSize;
 
	// 出力先を設定
	z.next_out = dest;
	z.avail_out = destMaxSize;
 
	// 伸長(展開)
	status = inflate(&z, Z_NO_FLUSH);
	// 成功ではない、またはデータの最後まで読み取れていない場合は失敗
	if (status != Z_OK && status != Z_STREAM_END) {
		debugs_format(99, 5, "inflate: %s\n", (z.msg) ? z.msg : "???");
		return status;
	}
 
	// 出力サイズを設定
	*destSize = z.total_out;
 
	// 終了処理
	status = inflateEnd(&z);
	if (status != Z_OK) {
		debugs_format(99, 5, "inflateEnd: %s\n", (z.msg) ? z.msg : "???");
		return status;
	}
 
	// 出力サイズを設定
	*destSize = z.total_out;
 
	return status;
}

MLEXP. Wiki


トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS