Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

os.stat information about a file or directory (file exists)

  • os
  • IsNotExist
  • Stat
package main

import (
	"fmt"
	"os"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Printf("Usage %s FILENAME\n", os.Args[0])
		os.Exit(1)
	}
	var filename = os.Args[1]
	var st, err = os.Stat(filename)
	if err != nil {
		fmt.Printf("Error: %s\n", err)
		if os.IsNotExist(err) {
			fmt.Printf("IsNotExist\n")
		}
		os.Exit(1)
	}
	fmt.Println(st)
	fmt.Printf("Name: %s\n", st.Name())
	fmt.Printf("Size: %d\n", st.Size())
}
Error: stat hello/world: no such file or directory

If the directory where the file can be found is not executable by the user who runs this code, we'll get the following error:

Error: stat hello/world: permission denied