Skip to content

FileOpen

Description

Open a file. mode is libc-compatible: "r"/"rb", "w"/"wb", "a"/"ab", "r+"/"rb+"/"r+b", "w+", "a+". Binary is always implied; the "b" suffix is accepted for compatibility but has no effect on the implementation.

Success

Returns a File where FileIsValid(&out) is true.

Failure

Returns a File where FileIsValid(&out) is false.

Usage example (Cross-references)

Usage examples (Cross-references)
    
    static bool path_exists(const char *path) {
        File f = FileOpen(path, "rb");
        if (!FileIsValid(&f)) {
            return false;
    
    static bool path_exists(const char *path) {
        File f = FileOpen(path, "rb");
        if (!FileIsValid(&f)) {
            return false;
    // Check whether `path` exists and is non-empty.
    static bool path_exists(const char *path) {
        File f = FileOpen(path, "rb");
        if (!FileIsValid(&f)) {
            return false;
        // buffer size and short-circuits to empty — we have to loop-read
        // into a growing buffer ourselves.
        File f = FileOpen("/proc/self/maps", "rb");
        if (!FileIsValid(&f)) {
            LOG_ERROR("ProcMapsLoad: FileOpen(/proc/self/maps) failed");
        File f = FileOpen("/proc/self/maps", "rb");
        if (!FileIsValid(&f)) {
            LOG_ERROR("ProcMapsLoad: FileOpen(/proc/self/maps) failed");
            ProcMapsDeinit(out);
            return false;
        (void)mode;
        (void)out_flags;
        return false; // Windows uses a different mode encoding (see FileOpen).
    #else
        if (!mode || !*mode) {
    // ---------------------------------------------------------------------------
    
    File FileOpen(const char *path, const char *mode) {
        File f = {0};
    #ifdef _WIN32
        HANDLE h = CreateFileA(path, access, FILE_SHARE_READ, NULL, disposition, FILE_ATTRIBUTE_NORMAL, NULL);
        if (h == INVALID_HANDLE_VALUE) {
            LOG_ERROR("FileOpen: CreateFileA(\"{}\") failed (err {})", path, (u32)GetLastError());
            return f;
        }
        int flags;
        if (!parse_open_mode(mode, &flags)) {
            LOG_ERROR("FileOpen: invalid mode \"{}\"", mode);
            return f;
        }
    #    endif
        if (fd < 0) {
            LOG_ERROR("FileOpen: open(\"{}\") failed (errno {})", path, (i32)-fd);
            return f;
        }
        }
    
        File f = FileOpen(filename, "rb");
        if (!FileIsValid(&f)) {
            return false;
        }
    
        File elf = FileOpen(argv[1], "rb");
        if (!FileIsValid(&elf)) {
            LOG_ERROR("Failed to open file for reading.");
Last updated on