Standard library / os
os.NewFile()
Wraps an existing descriptor or handle; Close takes responsibility for that descriptor. Do not wrap a borrowed descriptor and close both wrappers. This example duplicates a temporary file descriptor first on Unix. Example intended for Linux/AMD64 with Go 1.23.2 in a disposable working directory; other platforms may differ. Expected stdout: 'ok\n'.
Formal Syntax & Structure
go syntaxgo
func NewFile(fd uintptr, name string) *FileParameters & Attributes
| Name | Type | Description |
|---|---|---|
| fd | uintptr | Existing descriptor or handle. |
| name | string | File or executable name, according to the operation. |
Return Value
*File
Wraps an existing descriptor or handle; Close takes responsibility for that descriptor.
Working Example
Example Snippetgo
package main
import ( "fmt" "os" "syscall")
func must(e error) { if e != nil { panic(e) }}func temp() *os.File { f, e := os.CreateTemp(".", "fixture-"); must(e); return f }func main() { f := temp() defer os.Remove(f.Name()) defer f.Close() fd, e := syscall.Dup(int(f.Fd())) must(e) g := os.NewFile(uintptr(fd), "duplicate") if g == nil { panic("invalid descriptor") } must(g.Close()) _, e = f.WriteString("ok") must(e) fmt.Println("ok")}