#open/read file
1 messages · Page 1 of 1 (latest)
here's some code that's should make it work.
const file = std.fs.cwd().openFile("your_file", .{}) catch |err| {
switch(err) {
.FileNotFound => {},
else => {},
}
};
const content = try file.readToEndAlloc(alloc, max_bytes);
However keep in mind that cwd() uses the current working directory and many things are context dependened.
(i would also strongly recommend trying to figure it out yourself, before just blindly copy + pasting this)
theres like 7 different file opening functions but they all do basically the same thing, really only different how theyre called
thanks , what i am supposed to put in the flags parameter ?
zig's std code is very readable, why not try and read it? :)
(in the docs, you can click on the flags type, and there you get further information on that type)
i tried and found that : pub const OpenMode = enum { read_only, write_only, read_write, }; but it doesn't work
why can't this work with the args ?
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
var argc = args.len;
if (argc < 2) {
std.log.err("Usage: {} script file\n", args[0]);
return;
}
var file = try std.fs.cwd().openFile(args[0], .{});
defer file.close();```
I think i need to cast the arg to a const u8 ?
std.log.err("Usage: {} script file\n", args[0]); has to be
std.log.err("Usage: {s} script file\n", .{args[0]});
yeah it does that sometimes, I imagine it's something that can/will be changed
Yup I'd also believe that.
You can compile with -freference-trace to see the full trace.
I can't get this to work why ? I tried a lot of things
var file = std.fs.cwd().openFile(args[0], .{}) catch |err| {
switch (err) {
.FileNotFound => {
return;
},
else => {},
}
};
defer file.close();```
```zig build-exe MyRadarZig Debug native 1 errors
src/main.zig:31:14: error: expected type 'error{AccessDenied,BadPathName,DeviceBusy,FileBusy,FileLocksNotSupported,FileNotFound,FileTooBig,InvalidHandle,InvalidUtf8,IsDir,NameTooLong,NoDevice,NoSpaceLeft,NotDir,PathAlreadyExists,PipeBusy,ProcessFdQuotaExceeded,SharingViolation,SymLinkLoop,SystemFdQuotaExceeded,SystemResources,Unexpected,WouldBlock}', found '@TypeOf(.enum_literal)'
.FileNotFound => {
~^~~~~~~~~~~~```
you have to do error.FileNotFound in the switch
var file = std.fs.cwd().openFile(args[0], .{}) catch |err| {
switch (err) {
error.FileNotFound => {
return;
},
else => {},
}
};
defer file.close();```
Still doesn't work
