Skip to content

FileFromFd

Description

Borrow a POSIX fd into a File. The returned File has owns = false so FileClose is a no-op on it. Use for wrapping the well-known standard streams or fds you got from elsewhere.

Success

POSIX – returns a File whose underlying handle aliases fd and whose owns flag is false; FileIsOpen is true unless fd was negative.

Failure

POSIX cannot fail; an invalid fd produces a File that simply reports as not-open. Windows has no fd concept; FileFromFd always returns an INVALID_HANDLE_VALUE File regardless of the fd value – use FileStdin / FileStdout / FileStderr for the standard streams on Windows.

Usage example (Cross-references)

Usage examples (Cross-references)
        StrAppendFmt(&full, "[{}] [{}:{}] {}\n", (Zstr)NAMES[type], (Zstr)tag, line, (Zstr)msg);
    
        File out = (type == LOG_MESSAGE_TYPE_INFO) ? FileFromFd(1) : FileFromFd(2);
        (void)FileWrite(&out, StrBegin(&full), StrLen(&full));
    }
    
    File FileFromFd(i32 fd) {
        File f = {0};
    #if PLATFORM_WINDOWS
        return f;
    #else
        return FileFromFd(0);
    #endif
    }
        return f;
    #else
        return FileFromFd(1);
    #endif
    }
        return f;
    #else
        return FileFromFd(2);
    #endif
    }
    // it back. A constant 42 would surface 42 regardless of the argument.
    bool test_fm_172_fromfd_keeps_fd(void) {
        WriteFmt("Testing FileFromFd preserves the fd value (FileFd round-trip)\n");
    
    #if PLATFORM_WINDOWS
    #else
        // fd 1 (stdout) is a stable, known descriptor.
        File f  = FileFromFd(1);
        bool ok = (FileFd(&f) == 1);
        // A different fd surfaces distinctly too.
        bool ok = (FileFd(&f) == 1);
        // A different fd surfaces distinctly too.
        File g = FileFromFd(0);
        ok     = ok && (FileFd(&g) == 0);
        return ok;
    // temp file, FileClose the borrowed wrapper, then keep using the owner.
    bool test_fm_173_fromfd_does_not_own(void) {
        WriteFmt("Testing FileFromFd borrows (owns=false): close is a no-op on the fd\n");
    
        DefaultAllocator alloc      = DefaultAllocatorInit();
        // the fd is left open; if the mutant set owns=true, this close would
        // really close the fd and the subsequent owner write would fail.
        File borrowed = FileFromFd(FileFd(&owner));
        FileClose(&borrowed);
        // fd 0 (stdin) is a valid, open descriptor. `>= 0` must accept it;
        // a `> 0` mutant would wrongly report it not-open.
        File f  = FileFromFd(0);
        bool ok = (FileIsOpen(&f) == true);
        // Sanity: a genuinely-negative fd is not open under either form, so
        // Sanity: a genuinely-negative fd is not open under either form, so
        // the discriminating case really is fd == 0.
        File g = FileFromFd(-1);
        ok     = ok && (FileIsOpen(&g) == false);
        return ok;
Last updated on