Zig
Zig
Add Text Files to a ZIP Using AddString
See more Zip Examples
This example demonstrates how to use the AddString method to add multiple text files directly from string variables into a ZIP archive.
Each string is converted to bytes using the specified character encoding and stored as a separate file entry within the ZIP archive.
This method is useful for dynamically generating small text files such as configuration files, reports, JSON documents, XML, or log files entirely in memory.
Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
const zip = try chilkat.Zip.init();
defer zip.deinit();
zip.newZip("stringEntries.zip") catch {
std.debug.print("{s}\n", .{try zip.getLastErrorText(alloc)});
return;
};
// Add a README text file.
const readme_text = "This ZIP archive was created using AddString.";
zip.addString("docs/readme.txt", readme_text, "utf-8") catch {
std.debug.print("{s}\n", .{try zip.getLastErrorText(alloc)});
return;
};
// Add a JSON configuration file.
const json_text = "{ \"server\": \"example.com\", \"port\": 443 }";
zip.addString("config/settings.json", json_text, "utf-8") catch {
std.debug.print("{s}\n", .{try zip.getLastErrorText(alloc)});
return;
};
// Add a small XML document.
const xml_text = "<root><status>OK</status></root>";
zip.addString("xml/status.xml", xml_text, "utf-8") catch {
std.debug.print("{s}\n", .{try zip.getLastErrorText(alloc)});
return;
};
// Write the ZIP archive to disk and close it.
zip.writeZipAndClose() catch {
std.debug.print("{s}\n", .{try zip.getLastErrorText(alloc)});
return;
};
std.debug.print("ZIP archive created successfully.\n", .{});
}