golang 獲取當前路徑和上一級父路徑(目錄)

pengfoo發表於2014-04-04

golang 獲取當前路徑和上一級父路徑(目錄)

package main

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

func substr(s string, pos, length int) string {
	runes := []rune(s)
	l := pos + length
	if l > len(runes) {
		l = len(runes)
	}
	return string(runes[pos:l])
}

func getParentDirectory(dirctory string) string {
	return substr(dirctory, 0, strings.LastIndex(dirctory, "/"))
}

func getCurrentDirectory() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Fatal(err)
	}
	return strings.Replace(dir, "\\", "/", -1)
}

func main() {

	var str1, str2 string
	str1 = getCurrentDirectory()

	str2 = getParentDirectory(str1)
	fmt.Println(str2)

}


 

 

相關文章