Files, Directories and Processes

21.1 Files

const fs = std.fs;

// Read an entire file
const content = try fs.cwd().readFileAlloc(allocator, "data.txt", 10 * 1024 * 1024);   // max size
defer allocator.free(content);

// Write a file
try fs.cwd().writeFile(.{ .sub_path = "out.txt", .data = "Hello\n" });

// Open, create, and append
const file = try fs.cwd().createFile("log.txt", .{ .truncate = false });
defer file.close();
try file.seekFromEnd(0);
try file.writeAll("appended line\n");

const f2 = try fs.cwd().openFile("data.txt", .{ .mode = .read_only });
defer f2.close();
const stat = try f2.stat();
std.debug.print("size: {d}\n", .{stat.size});
var small: [128]u8 = undefined;
const n = try f2.read(&small);
_ = n;

21.2 Directories and Paths

try fs.cwd().makePath("build/out/assets");                // mkdir -p
try fs.cwd().deleteTree("build");
try fs.cwd().rename("old.txt", "new.txt");
try fs.cwd().deleteFile("tmp.txt");
try fs.cwd().copyFile("a.txt", fs.cwd(), "b.txt", .{});

var dir = try fs.cwd().openDir("src", .{ .iterate = true });
defer dir.close();
var it = dir.iterate();
while (try it.next()) |entry| std.debug.print("{s} ({s})\n", .{ entry.name, @tagName(entry.kind) });

var walker = try dir.walk(allocator);                    // recursive
defer walker.deinit();
while (try walker.next()) |entry| std.debug.print("{s}\n", .{entry.path});

const joined = try fs.path.join(allocator, &.{ "dir", "sub", "file.txt" });
defer allocator.free(joined);
_ = fs.path.basename(joined);
_ = fs.path.dirname(joined);
_ = fs.path.extension(joined);
const abs = try fs.cwd().realpathAlloc(allocator, ".");
defer allocator.free(abs);
const exe_dir = try fs.selfExeDirPathAlloc(allocator);
defer allocator.free(exe_dir);

21.3 Command-Line Arguments and Environment

const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
for (args, 0..) |arg, i| std.debug.print("{d}: {s}\n", .{ i, arg });

var env = try std.process.getEnvMap(allocator);
defer env.deinit();
if (env.get("HOME")) |home| std.debug.print("{s}\n", .{home});
const path = std.process.getEnvVarOwned(allocator, "PATH") catch null;
if (path) |p| allocator.free(p);
std.process.exit(0);

21.4 Running Child Processes

const result = try std.process.Child.run(.{
    .allocator = allocator,
    .argv = &.{ "git", "--version" },
});
defer allocator.free(result.stdout);
defer allocator.free(result.stderr);
std.debug.print("exit: {any}\n{s}", .{ result.term, result.stdout });

var child = std.process.Child.init(&.{ "ls", "-la" }, allocator);
child.stdout_behavior = .Inherit;
const term = try child.spawnAndWait();
_ = term;