temporary files and directories

temporary files and directories

原文:https://gobyexample.com/temporary-files-and-directories

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Note:
// This code is from https://gobyexample.com.
package main

import (
	"fmt"
	"path/filepath"
	"strings"
)

func main() {
	p := filepath.Join("dir1", "dir2", "filename")
	fmt.Println("p:", p) // p: dir1\dir2\filename

	fmt.Println(filepath.Join("dir1//", "filename"))       // dir1\filename
	fmt.Println(filepath.Join("dir1/../dir1", "filename")) // dir1\filename

	fmt.Println("Dir(p):", filepath.Dir(p))   // Dir(p): dir1\dir2
	fmt.Println("Base(p):", filepath.Base(p)) // Base(p): filename

	fmt.Println(filepath.IsAbs("dir/file"))  // false
	fmt.Println(filepath.IsAbs("/dir/file")) // false

	filename := "config.json"

	ext := filepath.Ext(filename)
	fmt.Println(ext) // .json

	fmt.Println(strings.TrimSuffix(filename, ext)) // config

	rel, err := filepath.Rel("a/b", "a/b/t/file")
	if err != nil {
		panic(err)
	}
	fmt.Println(rel) // t\file

	rel, err = filepath.Rel("a/b", "a/c/t/file")
	if err != nil {
		panic(err)
	}
	fmt.Println(rel) // ..\c\t\file
}
最后修改 March 10, 2024: 更新 (ddf4687)