Skip to content

FileFd

Description

Return the underlying fd. POSIX-only; on Windows the handle is a HANDLE and there is no fd to surface.

Success

Returns the fd (>= 0) on POSIX.

Failure

Returns -1 on Windows, or for a File that isn’t open.

Usage example (Cross-references)

Usage examples (Cross-references)
    }
    
    i32 FileFd(const File *f) {
    #if PLATFORM_WINDOWS
        (void)f;
    
        Str buffer = StrInit(&scratch);
        i32 fd     = FileFd(file);
    
        // Probe seekability: if FileSeek(0, CUR) succeeds, the underlying
    // 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
        // fd 1 (stdout) is a stable, known descriptor.
        File f  = FileFromFd(1);
        bool ok = (FileFd(&f) == 1);
        // A different fd surfaces distinctly too.
        File g = FileFromFd(0);
        // A different fd surfaces distinctly too.
        File g = FileFromFd(0);
        ok     = ok && (FileFd(&g) == 0);
        return ok;
    #endif
        // 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);
        }
    
        i32 fd_a = FileFd(&a);
    
        // Really close A. On clean source this frees fd_a; the ge_to_lt mutant
        File c     = FileOpenTemp(&pc, alloc_base);
        ok         = ok && FileIsOpen(&c);
        i32  fd_c  = FileFd(&c);
        bool reuse = (fd_c == fd_a);
Last updated on