Golang : How to get Unix file descriptor for console and file
A short tutorial showing you how to obtain the Unix file descriptor for terminal/console and file in Golang with the os
package. Basically, there are 3 file descriptors under Unix/Linux environment :
- 0 for input
- 1 for output
- 3 for file
and knowing this information can be helpful in situation when you want to test if a given variable is a file or console.
Here we go!
package main
import (
"fmt"
"os"
)
func main() {
// get console unix file descriptor
outputFileDesc := int(os.Stdout.Fd())
outputName := os.Stdout.Name()
fmt.Println("Terminal or console output Unix file descriptor : ", outputFileDesc)
fmt.Println("output Unix file descriptor name : ", outputName)
fmt.Println("------------------------")
inputFileDesc := int(os.Stdin.Fd())
inputName := os.Stdin.Name()
fmt.Println("Terminal or console input Unix file descriptor : ", inputFileDesc)
fmt.Println("input Unix file descriptor name : ", inputName)
fmt.Println("------------------------")
// get a file unix file descriptor
file, err := os.Open("file.data")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fileDescriptor := int(file.Fd()) // get the unix descriptor
fileDescriptorName := file.Name() // get the file name
file.Close()
fmt.Printf("%s Unix file descriptor : %d \n", fileDescriptorName, fileDescriptor)
}
Output :
Terminal or console output Unix file descriptor : 1
output Unix file descriptor name : /dev/stdout
------------------------
Terminal or console input Unix file descriptor : 0
input Unix file descriptor name : /dev/stdin
------------------------
file.data Unix file descriptor : 3
Happy coding!
References :
https://golang.org/pkg/os/#File.Fd
https://socketloop.com/references/golang-os-file-fd-function-example
http://www.theunixschool.com/2010/08/unix-file-descriptors.html
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.4k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+11.1k Golang : Byte format example
+8.6k Golang : Accept any number of function arguments with three dots(...)
+16.4k Golang : Read integer from file into array
+9.2k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+9.3k Golang : How to extract video or image files from html source code
+10k Golang : Text file editor (accept input from screen and save to file)
+4.5k Chrome : How to block socketloop.com links in Google SERP?
+5.1k Golang : Get FX sentiment from website example
+9k Golang : How to control fmt or log print format?
+14.7k Golang : Search folders for file recursively with wildcard support
+21.5k Golang : Setting up/configure AWS credentials with official aws-sdk-go