Sample code for 30+ languages & platforms
Unicode 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 Unicode C Downloads

Unicode C
#include <C_CkGzipW.h>
#include <C_CkStringBuilderW.h>
#include <C_CkBinDataW.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkGzipW gzip;
    HCkStringBuilderW sb;
    HCkBinDataW 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 = CkGzipW_Create();
    sb = CkStringBuilderW_Create();
    bd = CkBinDataW_Create();

    // Add some text to the StringBuilder:
    CkStringBuilderW_Append(sb,L"The quick brown fox jumps over the lazy dog.");

    // Compress the text using UTF-8 encoding:
    success = CkGzipW_CompressSb(gzip,sb,L"utf-8",bd);
    if (success == FALSE) {
        wprintf(L"%s\n",CkGzipW_lastErrorText(gzip));
        CkGzipW_Dispose(gzip);
        CkStringBuilderW_Dispose(sb);
        CkBinDataW_Dispose(bd);
        return;
    }

    // The BinData now contains the Gzip-compressed bytes.
    wprintf(L"Compression successful.\n");
    wprintf(L"Compressed size (bytes): %d\n",CkBinDataW_getNumBytes(bd));

    // (Optional) Save to a .gz file:
    success = CkBinDataW_WriteFile(bd,L"text.gz");
    if (success == FALSE) {
        wprintf(L"%s\n",CkBinDataW_lastErrorText(bd));
        CkGzipW_Dispose(gzip);
        CkStringBuilderW_Dispose(sb);
        CkBinDataW_Dispose(bd);
        return;
    }

    wprintf(L"Gzip file written to text.gz\n");


    CkGzipW_Dispose(gzip);
    CkStringBuilderW_Dispose(sb);
    CkBinDataW_Dispose(bd);

    }