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
+8.5k Golang : Qt get screen resolution and display on center example
+13.5k Golang : Find commonalities in two slices or arrays example
+6.7k Gogland : Where to put source code files in package directory for rookie
+14.9k Golang : convert string or integer to big.Int type
+19.2k Golang : Pipe output from one os.Exec(shell command) to another command
+14.4k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+4.8k Golang : Struct field tags and what is their purpose?
+7.6k Android Studio : Indicate progression with ProgressBar example
+10.3k Golang : How to flush a channel before the end of program?
+13.4k Golang : Submit web forms without browser by http.PostForm example
+19.9k Golang : Get password from console input without echo or masked
+5.8k Default cipher that OpenSSL used to encrypt a PEM file