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.1k Golang : Detect number of active displays and the display's resolution
+4.2k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+5.7k Golang : Warp text string by number of characters or runes example
+21.7k Golang : Randomly pick an item from a slice/array example
+7.6k Golang : Set or add headers for many or different handlers
+5k Fontello : How to load and use fonts?
+10k How to test Facebook App on localhost ?
+11k Android Studio : Highlight ImageButton when pressed on example
+4.8k Golang : Denco multiplexer example
+4.5k Golang : Display advertisement images or strings on random order
+27.7k Golang : Get first few and last few characters from string