How to write a text file with Zig

Let’s write the kids’ poem twinkle twinkle little star with Zig.

const std = @import("std");

pub fn main() anyerror!void {
    // Open the file
    var file = try std.fs.cwd().createFile("output.txt", .{});
    defer file.close();

    // Write the contents
    try file.writeAll("Twinkle, twinkle, little star,\nHow I wonder what you are!\nUp above the world so high,\nLike a diamond in the sky.\n");
}
Zig

Here’s a detailed explanation of each line of code:

  • const std = @import("std");: This line imports the standard library module.
  • pub fn main() anyerror!void {: This line defines the main function.
  • var file = try std.fs.cwd().createFile("output.txt", .{});: This line creates a new file named “output.txt” in the current working directory.
  • defer file.close();: This line defers closing the file until the end of the function.
  • try file.writeAll("Twinkle, twinkle, little star,\nHow I wonder what you are!\nUp above the world so high,\nLike a diamond in the sky.\n");: This line writes “Twinkle Twinkle Little Star” to the file.

Need further assistance, paid dedicated one-to-one tutor, need assignments done or have a paid project in Zig?

Leave a Reply

Your email address will not be published. Required fields are marked *