How to open/create a file/read from a file (n line at a time)/write to a file (in the new Io.Dir)?

All of the topics I’ve searched is std.fs, can you give me a sample of:

  1. Opening/Creating a file in the new (Io.Dir)?

  2. Reading a file (n line at a time)

  3. Writing to a file

I did get into opening a file, but couldn’t give the 2nd parameter (std.Io)?

What i did was

const file = try std.Io.Dir.createFile(std.Io.Dir.cwd(), 'std.Io', cfgfile, .{.read=true});

(post deleted by author)

1 Like

Here’s my $2c.

const std = @import("std");
const fs = std.fs;

pub fn main() !void {

    // opening or creating a file at a absolute path
    const file = try fs.createFileAbsolute("/tmp/test.txt", .{ .read = true });
    var threaded: std.Io.Threaded = .init_single_threaded;
    const io = threaded.ioBasic();
    const buf_siz = 1024 * 4; // 4K
    var buffer: [buf_siz]u8 = undefined;
    var file_reader = file.reader(io, &buffer);
    var file_writer = file.writer(&buffer);

    // writing to the file
    try file_writer.end();
    try file_writer.interface.writeAll("first line;\n");
    try file_writer.interface.writeAll("second line;\n");
    try file_writer.interface.writeAll("third line.\n");
    try file_writer.interface.flush();

    // reading & printing the lines
    try file_reader.seekTo(0);
    // here I am taking on account that buffer if big enough to hold all lines
    try file_reader.interface.fillMore();
    const new_line = 10;
    var line = (try file_reader.interface.takeDelimiter(new_line)).?;
    std.debug.print("line 1: {s}\n", .{line});
    line = (try file_reader.interface.takeDelimiter(new_line)).?;
    std.debug.print("line 2: {s}\n", .{line});
    line = (try file_reader.interface.takeDelimiter(new_line)).?;
    std.debug.print("line 3: {s}\n", .{line});


    // deleting the created test file
    var dir = try std.fs.openDirAbsolute("/tmp", .{});
    defer dir.close();
    try dir.deleteFile("test.txt");
}

@Austin I don’t know, the second param is giving me an error, seems a struct but it needs the vtable field…

note: missing struct field: vtable

@kalapalo What’s the difference between std.fs.Dir.openFile and std.Io.Dir.openFile. I know that std.Io.Dir.openFile is the new way moving forwards…

Yeah, std.fs.Dir.Openfile is deprecated and std.Io.Dir.openFile is the way to go.

Ah.

My eyes deceived me. I’m very much not using Io.Dir either.
Something I’d update when 16 is no longer dev.

Disregard my answer.