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
+13.8k Golang : Basic authentication with .htpasswd file
+32.4k Golang : How to check if slice or array is empty?
+3.9k Golang : Customize scanner.Scanner to treat dash as part of identifier
+15k Golang : How to extract links from web page ?
+17.8k Golang : How to make function callback or pass value from function as parameter?
+11.1k Golang : Add ASCII art to command line application launching process
+6k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+19.2k Golang : Pipe output from one os.Exec(shell command) to another command
+7.8k Golang : Heap sort example
+10.8k Golang : Determine if time variables have same calendar day
+5.5k Golang : Embedded or data bundling example
+3.5k Golang : Valued expressions and functions example