こんにちは、kurumi-bioです。
第12回目のosパッケージ(標準ライブラリー)の学習です。
環境
- Windows
OSバージョン:Windows11 Home 22H2
Go言語のバージョン:go version go1.20 windows/amd64 - Linux
OSバージョン:openSUSE Leap 15.4
Go言語のバージョン:go version go1.20.1 linux/amd64
Unsetenv関数
func Unsetenv(key string) error
◆テストコード
package main import ( "fmt" "os" ) func main() { e := os.Setenv("TEST", "TEST") if e != nil { fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("os.Setenv", e)) os.Exit(1) } fmt.Printf("TEST=[%s]\n", os.Getenv("TEST")) e = os.Unsetenv("TEST") if e != nil { fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("os.Setenv", e)) os.Exit(1) } fmt.Printf("TEST=[%s]\n", os.Getenv("TEST")) }
◆実行結果(Windows)
UserCacheDir関数
func UserCacheDir() (string, error)
◆テストコード
package main import ( "fmt" "os" ) func us() { e := os.Unsetenv("XDG_CACHE_HOME") if e != nil { fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("os.Unsetenv", e)) os.Exit(1) } } func se(path string) { e := os.Setenv("XDG_CACHE_HOME", path) if e != nil { fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("os.Setenv", e)) os.Exit(1) } } func ucd() { s, e := os.UserCacheDir() if e != nil { fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("os.UserCacheDir", e)) os.Exit(1) } fmt.Printf("UserCacheDir=[%s]\n", s) } func main() { us() ucd() se("~/go/nonDir") ucd() }
◆実行結果(Linux)
広告の下に続きます。
UserConfigDir関数
func UserConfigDir() (string, error)
◆テストコード
package main import ( "fmt" "os" ) func main() { fmt.Println(os.Getenv("AppData")) s, e := os.UserConfigDir() if e != nil { fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("os.UserConfigDir", e)) os.Exit(1) } fmt.Println(s) }
◆実行結果(Windows)
UserHomeDir関数
func UserHomeDir() (string, error)
◆テストコード
package main import ( "fmt" "os" ) func main() { s, e := os.UserHomeDir() if e != nil { fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("os.UserHomeDir", e)) os.Exit(1) } fmt.Printf("UserHomeDir=[%s]\n", s) }
◆実行結果(Linux)
WriteFile関数
func WriteFile(name string, data []byte, perm FileMode) error
◆テストコード
package main import ( "fmt" "os" ) func pm(fileName string) { f, e := os.Open(fileName) if e != nil { fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("os.Open", e)) os.Exit(1) } fi, se := f.Stat() if se != nil { fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("Stat", se)) os.Exit(1) } fmt.Printf("%v\n", fi.Mode().Perm()) } func rf(fileName string) { s, e := os.ReadFile(fileName) if e != nil { fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("os.ReadFile", e)) os.Exit(1) } fmt.Printf("[%s]\n", s) } func main() { const fileName = "writeFileTest.txt" os.Remove(fileName) e := os.WriteFile(fileName, []byte("Write Test"), 0666) if e != nil { fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("os.WriteFile", e)) os.Exit(1) } rf(fileName) pm(fileName) e = os.WriteFile(fileName, []byte("Write Test2"), 0600) if e != nil { fmt.Fprintf(os.Stderr, "%v\n", os.NewSyscallError("os.WriteFile", e)) os.Exit(1) } rf(fileName) pm(fileName) }
◆実行結果(Linux)
最後までご覧いただきありがとうございます