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
+6.6k Fix sudo yum hang problem with no output or error messages
+10.3k Golang : Get local time and equivalent time in different time zone
+52k Golang : How to get struct field and value by name
+11k Use systeminfo to find out installed Windows Hotfix(s) or updates
+4.4k Adding Skype actions such as call and chat into web page examples
+26k Golang : Calculate future date with time.Add() function
+6.2k PHP : Proper way to get UTF-8 character or string length
+5.8k Golang : How to verify input is rune?
+6.4k Golang : Join lines with certain suffix symbol example
+21.2k Golang : GORM create record or insert new record into database example
+4.7k Unix/Linux : secure copying between servers with SCP command examples
+16.8k Golang : Find file size(disk usage) with filepath.Walk