Write and Read file
...
...
Defining the Point Struct
defines a struct called Point with three fields:
- loc: a string representing the location of the point
- x: an integer representing the x-coordinate of the point
- y: an integer representing the y-coordinate of the point
const std = @import("std");
const print = std.debug.print;
const stdin = std.io.getStdIn().reader();
const Point = struct {
loc: []const u8,
x: i32,
y: i32,
};
main Function
defines a Point struct and creates a file called "point.txt". It then writes the point's location and coordinates to the file using the fileWrite.writer().print() function.
After writing to the file, it reads the file back using the fileRead.reader() function and prints the contents of the file to the console.
Note: The !void return type of the main function indicates that it may return an error. The try keyword is used to handle errors, and the defer keyword is used to ensure that resources are released when they are no longer needed.
Error Handling:
- The try keyword is used to handle errors that may occur when creating or opening files.
- The defer keyword is used to ensure that files are closed when they are no longer needed, even if an error occurs.
Resource Management:
- The defer keyword is used to ensure that resources are released when they are no longer needed.
- The try keyword is used to handle errors that may occur when releasing resources.
pub fn main() !void {
var p1: Point = undefined;
const filename = "point.txt";
var fileWrite = try std.fs.cwd().createFile(
filename,
.{ .truncate = false}
);
defer fileWrite.close();
try fileWrite.seekFromEnd(0);
// --WRITE--
p1.loc = "HOME";
p1.x = 10;
p1.y = 99;
try fileWrite.writer().print("{s} = {d} : {d}", .{p1.loc, p1.x, p1.y});
// --READ--
var fileRead = try std.fs.cwd().openFile(filename, .{});
defer fileRead.close();
try fileRead.seekTo(0);
var buffer: [1024]u8 = undefined;
const reader = fileRead.reader();
while (try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| {
print("{s}\n", .{line});
}
}
Outcome:
HOME = 10 : 99
Note:
The code assumes we input the file content via the program itself. For a variant of this code where we take user input and write to file, check this post.