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
+4.3k Get Facebook friends working in same company
+7.5k Golang : ISO8601 Duration Parser example
+9.1k Golang : Convert(cast) uintptr to string example
+3.5k Golang : Experimental emojis or emoticons icons programming language
+9.7k Golang : Query string with space symbol %20 in between
+13.9k Golang : Get command line arguments
+35.7k Golang : Marshal and unmarshal json.RawMessage struct example
+8.6k Golang : zlib compress file example
+3.7k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+7.1k Golang : interface - when and where to use examples
+3.3k Golang : fmt.Println prints out empty data from struct