Sample code for 30+ languages & platforms
Zig

Implement Preprocessor #include with StringBuilder

Demonstrates how to implement #include with a Chilkat StringBuilder.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // First build a string that has a preprocessor include
    const sb_src = try chilkat.StringBuilder.init();
    defer sb_src.deinit();
    sb_src.append("1\r\n2\r\n3\r\n") catch {};
    sb_src.append("#include <qa_data/txt/helloWorld.txt>\r\n") catch {};
    sb_src.append("4\r\n5\r\n") catch {};

    std.debug.print("{s}\n", .{try sb_src.getAsString(alloc)});

    // sbSrc contains:
    //     1
    //     2
    //     3
    //     #include <qa_data/txt/helloWorld.txt>
    //     4
    //     5

    // The qa_data/txt/helloWorld.txt file contains "Hello World!"

    const file_path = sb_src.getAfterBetween(alloc, "#include", "<", ">") catch {
        std.debug.print("No #include's found.\n", .{});
        return;
    };

    std.debug.print("filePath: {s}\n", .{file_path});

    // Load the contents of the filePath
    const sb_include_file = try chilkat.StringBuilder.init();
    defer sb_include_file.deinit();
    sb_include_file.loadFile(file_path, "utf-8") catch {};

    // Replace the first occurrence of #include <...> line with the contents of the include file.
    sb_src.replaceAllBetween("#include", ">", try sb_include_file.getAsString(alloc), true) catch {};

    std.debug.print("{s}\n", .{try sb_src.getAsString(alloc)});

    // sbSrce now contains:
    //     1
    //     2
    //     3
    //     Hello World!
    //     4
    //     5
}