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)
- In
Log.c:57:
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));- In
File.c:166:
}
File FileFromFd(i32 fd) {
File f = {0};
#if PLATFORM_WINDOWS- In
File.c:183:
return f;
#else
return FileFromFd(0);
#endif
}- In
File.c:192:
return f;
#else
return FileFromFd(1);
#endif
}- In
File.c:201:
return f;
#else
return FileFromFd(2);
#endif
}- In
File.c:483:
// 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- In
File.c:492:
#else
// fd 1 (stdout) is a stable, known descriptor.
File f = FileFromFd(1);
bool ok = (FileFd(&f) == 1);
// A different fd surfaces distinctly too.
- In
File.c:495:
bool ok = (FileFd(&f) == 1);
// A different fd surfaces distinctly too.
File g = FileFromFd(0);
ok = ok && (FileFd(&g) == 0);
return ok;- In
File.c:505:
// 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();- In
File.c:521:
// 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);- In
File.c:1132:
// 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
- In
File.c:1136:
// 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