C
C
Compress Text from StringBuilder to Gzip (BinData Output)
See more Gzip Examples
This example demonstrates how to use the CompressSb method to compress text stored in a StringBuilder into Gzip format.
The text is first converted to its byte representation using the specified character set (in this case, UTF-8). These bytes are then compressed, and the resulting Gzip data is written to a BinData object in memory.
This approach is useful when working with dynamically generated text that you want to compress without first writing it to a file. The example also shows how the compressed data can optionally be saved to a .gz file.
Chilkat C Downloads
#include <C_CkGzip.h>
#include <C_CkStringBuilder.h>
#include <C_CkBinData.h>
void ChilkatSample(void)
{
BOOL success;
HCkGzip gzip;
HCkStringBuilder sb;
HCkBinData bd;
success = FALSE;
// This example demonstrates how to compress text contained in a StringBuilder
// into Gzip format, storing the compressed result in a BinData object.
gzip = CkGzip_Create();
sb = CkStringBuilder_Create();
bd = CkBinData_Create();
// Add some text to the StringBuilder:
CkStringBuilder_Append(sb,"The quick brown fox jumps over the lazy dog.");
// Compress the text using UTF-8 encoding:
success = CkGzip_CompressSb(gzip,sb,"utf-8",bd);
if (success == FALSE) {
printf("%s\n",CkGzip_lastErrorText(gzip));
CkGzip_Dispose(gzip);
CkStringBuilder_Dispose(sb);
CkBinData_Dispose(bd);
return;
}
// The BinData now contains the Gzip-compressed bytes.
printf("Compression successful.\n");
printf("Compressed size (bytes): %d\n",CkBinData_getNumBytes(bd));
// (Optional) Save to a .gz file:
success = CkBinData_WriteFile(bd,"text.gz");
if (success == FALSE) {
printf("%s\n",CkBinData_lastErrorText(bd));
CkGzip_Dispose(gzip);
CkStringBuilder_Dispose(sb);
CkBinData_Dispose(bd);
return;
}
printf("Gzip file written to text.gz\n");
CkGzip_Dispose(gzip);
CkStringBuilder_Dispose(sb);
CkBinData_Dispose(bd);
}