Skip to content

Instantly share code, notes, and snippets.

@kojix2
Created May 8, 2024 06:36
Show Gist options
  • Save kojix2/bd9523fdd3c1e7f8be4ce2c91fd17435 to your computer and use it in GitHub Desktop.
Save kojix2/bd9523fdd3c1e7f8be4ce2c91fd17435 to your computer and use it in GitHub Desktop.
Generate gzip file for testing Compress::Gzip ver1
#include <stdio.h>
#include <string.h>
#include <zlib.h>
#include <time.h>
int main()
{
char *filename = "test.gz";
char *contents = "One\nTwo";
int content_length = strlen(contents);
unsigned char outbuffer[4096];
FILE *file;
z_stream strm;
gz_header header;
// Set a fixed UTC timestamp
struct tm t;
t.tm_year = 2012 - 1900;
t.tm_mon = 8;
t.tm_mday = 4;
t.tm_hour = 22;
t.tm_min = 6;
t.tm_sec = 5;
t.tm_isdst = -1; // Disable daylight saving time handling
// Use timegm instead of mktime to convert to UTC
time_t fixed_time = timegm(&t);
// Initialize header information
memset(&header, 0, sizeof(header));
header.text = 1;
header.time = fixed_time;
header.os = 0x03;
header.name = (Bytef *)"test.txt";
header.comment = (Bytef *)"happy birthday";
Bytef extra[] = {0x01, 0x02, 0x03, 0x04, 0x05};
header.extra = extra;
header.extra_len = sizeof(extra);
header.hcrc = 1; // Enable CRC check
// Initialize deflate stream
memset(&strm, 0, sizeof(strm));
deflateInit2(&strm, Z_BEST_COMPRESSION, Z_DEFLATED, MAX_WBITS + 16, 8, Z_DEFAULT_STRATEGY);
// Set header
deflateSetHeader(&strm, &header);
// Set input data
strm.next_in = (Bytef *)contents;
strm.avail_in = content_length;
// Open output file
file = fopen(filename, "wb");
// Compress and write output
int ret;
do
{
strm.avail_out = sizeof(outbuffer);
strm.next_out = outbuffer;
ret = deflate(&strm, Z_FINISH);
fwrite(outbuffer, 1, sizeof(outbuffer) - strm.avail_out, file);
} while (ret != Z_STREAM_END);
// Finalize
deflateEnd(&strm);
fclose(file);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment