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
+16.7k Golang : Read integer from file into array
+25.8k Golang : How to read integer value from standard input ?
+28.1k Golang : Connect to database (MySQL/MariaDB) server
+11.9k Golang : Determine if time variables have same calendar day
+11k Golang : Simple image viewer with Go-GTK
+5.2k Golang : The Tao of importing package
+32.6k Golang : Regular Expression for alphanumeric and underscore
+19.5k Golang : Example for DSA(Digital Signature Algorithm) package functions
+20.6k Golang : Secure(TLS) connection between server and client
+8.2k Golang : Auto-generate reply email with text/template package
+5.3k Golang : Reclaim memory occupied by make() example
+8.2k Golang : Configure Apache and NGINX to access your Go service example