Tcl
Tcl
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 Tcl Downloads
load ./chilkat.dll
set success 0
# This example demonstrates how to compress text contained in a StringBuilder
# into Gzip format, storing the compressed result in a BinData object.
set gzip [new_CkGzip]
set sb [new_CkStringBuilder]
set bd [new_CkBinData]
# 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:
set success [CkGzip_CompressSb $gzip $sb "utf-8" $bd]
if {$success == 0} then {
puts [CkGzip_lastErrorText $gzip]
delete_CkGzip $gzip
delete_CkStringBuilder $sb
delete_CkBinData $bd
exit
}
# The BinData now contains the Gzip-compressed bytes.
puts "Compression successful."
puts "Compressed size (bytes): [CkBinData_get_NumBytes $bd]"
# (Optional) Save to a .gz file:
set success [CkBinData_WriteFile $bd "text.gz"]
if {$success == 0} then {
puts [CkBinData_lastErrorText $bd]
delete_CkGzip $gzip
delete_CkStringBuilder $sb
delete_CkBinData $bd
exit
}
puts "Gzip file written to text.gz"
delete_CkGzip $gzip
delete_CkStringBuilder $sb
delete_CkBinData $bd