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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| package main
import ( "bufio" "fmt" "os" "path" "path/filepath" )
func PathExists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err }
func WriteConfig(mfilepath string) { strArr := new([]string) *strArr = append(*strArr, "111") *strArr = append(*strArr, "222") *strArr = append(*strArr, "333")
DicPath := filepath.Dir(mfilepath) fmt.Print("DicPath:", DicPath)
isExist, _ := PathExists(DicPath) if !isExist { os.MkdirAll(DicPath, os.ModePerm) }
file, err := os.OpenFile(mfilepath, os.O_WRONLY|os.O_CREATE, 0666) if err != nil { fmt.Println("文件打开失败", err) } defer file.Close() write := bufio.NewWriter(file) for i := 0; i < len(*strArr); i++ { write.WriteString((*strArr)[i] + "\n") } write.Flush() }
func main() { ExecPath, _ := os.Getwd() filepath2 := path.Join(ExecPath, "txt", "test.txt") WriteConfig(filepath2) }
|