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.3k Golang : does not implement flag.Value (missing Set method)
+20.8k Golang : How to run Golang application such as web server in the background or as daemon?
+12.7k Golang : Fix image: unknown format error
+7.9k Golang : Capture text return from exec function example
+4.5k Golang : If else example and common mistake
+16.5k How to enable MariaDB/MySQL logs ?
+15.8k Golang : Get number of CPU cores
+10.8k Golang : Split strings into command line arguments
+11.6k Golang : Get terminal width and height example
+15k Golang : Get IP addresses of a domain name
+7.5k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+6.5k Golang : Getting Echo framework StartAutoTLS to work