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
+9.3k Golang : How to get ECDSA curve and parameters data?
+30.1k Golang : Get time.Duration in year, month, week or day
+24.6k Golang : How to validate URL the right way
+16.5k Golang : Check if a string contains multiple sub-strings in []string?
+11.4k Golang : Concatenate (combine) buffer data example
+11.4k Golang : Post data with url.Values{}
+4.1k Detect if Google Analytics and Developer Media are loaded properly or not
+18.5k Golang : Logging with logrus
+6.9k Swift : substringWithRange() function example
+5.9k Golang : Use NLP to get sentences for each paragraph example
+18.9k Golang : How to make function callback or pass value from function as parameter?
+15.5k Golang : invalid character ',' looking for beginning of value