#open/read file

1 messages · Page 1 of 1 (latest)

royal topaz
#

Hi, how can i open and read a file and throw an error if it doesn't exist ?? I can't find anything on the internet

gaunt remnant
#

(i would also strongly recommend trying to figure it out yourself, before just blindly copy + pasting this)

flat moat
#

theres like 7 different file opening functions but they all do basically the same thing, really only different how theyre called

royal topaz
#

thanks , what i am supposed to put in the flags parameter ?

gaunt remnant
#

(in the docs, you can click on the flags type, and there you get further information on that type)

royal topaz
#

i tried and found that : pub const OpenMode = enum { read_only, write_only, read_write, }; but it doesn't work

royal topaz
#

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 ?
flat moat
#

std.log.err("Usage: {} script file\n", args[0]); has to be
std.log.err("Usage: {s} script file\n", .{args[0]});

royal topaz
#

thank you zeroLike

#

it's annoying that errors don't refer to my code

flat moat
#

yeah it does that sometimes, I imagine it's something that can/will be changed

gaunt remnant
primal bobcat
royal topaz
# gaunt remnant here's some code that's should make it work. ```rs const file = std.fs.cwd()...

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 => {
~^~~~~~~~~~~~```
flat moat
#

you have to do error.FileNotFound in the switch

royal topaz
flat moat
#

else => {} is of type void

#

youre basically telling the compiler to make file into nothing if any other error happens

royal topaz
#

ah fuck me

#

thanks