Golang *File points to a file or directory ?
In this tutorial, we will learn how to find out if the *File pointer is pointing to a file or directory. The codes are self explanatory
fileordir.go
package main
import (
"fmt"
"os"
"flag"
)
func main() {
flag.Parse()
fileordir := flag.Arg(0) // get first argument
file, err := os.Open(fileordir)
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
fileInfo, err := file.Stat()
if err != nil {
fmt.Println(err)
return
}
switch mode := fileInfo.Mode(); {
case mode.IsDir():
fmt.Println(fileordir + " is a directory")
case mode.IsRegular():
fmt.Println(fileordir + " is a file")
}
}
localhost:~ admin$ go run fileordir.go /Users/admin/for
/Users/admin/for is a file
localhost:~ admin$ go run fileordir.go /Users/admin
/Users/admin is a directory
Hope this can be useful.
See also : Golang : Copy directory - including sub-directories and files
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
+13.6k Golang : Activate web camera and broadcast out base64 encoded images
+7.9k Golang : Grayscale Image
+7.9k Golang : Handle Palindrome string with case sensitivity and unicode
+15.6k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+52.4k Golang : How to get struct field and value by name
+9.5k Javascript : Read/parse JSON data from HTTP response
+7.9k Golang : What fmt.Println() can do and println() cannot do
+10.5k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+8.2k Golang : Check if integer is power of four example
+14.4k Golang : Rename directory
+15.2k Golang : How to get Unix file descriptor for console and file
+7.1k Golang : Use modern ciphers only in secure connection