码迷,mamicode.com
首页 > 其他好文 > 详细

Golang获得执行文件的当前路径

时间:2016-07-15 13:23:51      阅读:956      评论:0      收藏:0      [点我收藏+]

标签:

运行环境:
golang1.4.2+win7x64
golang1.4.2+centos6.5×64

 1 package Helper    
 2     
 3 import (    
 4     “os”    
 5     “os/exec”    
 6     “path/filepath”    
 7     “strings”    
 8 )    
 9     
10 /*获取当前文件执行的路径*/    
11 func GetCurPath() string {    
12     file, _ := exec.LookPath(os.Args[0])    
13   
14     //得到全路径,比如在windows下E:\\golang\\test\\a.exe  
15     path, _ := filepath.Abs(file)       
16   
17     //将全路径用\\分割,得到4段,①E: ②golang ③test ④a.exe  
18     splitstring := strings.Split(path, “\\”)        
19              
20     //size为4 
21     size := len(splitstring)           
22  
23     //将全路径用最后一段(④a.exe)进行分割,得到2段,①E:\\golang\\test\\ ②a.exe 
24     splitstring = strings.Split(path, splitstring[size-1])     
25  
26     //将①(E:\\golang\\test\\)中的\\替换为/,最终得到结果E:/golang/test/ 
27     rst := strings.Replace(splitstring[0], “\\“, “/”, size-1)     
28     return rst    
29 }

 

Golang获得执行文件的当前路径

标签:

原文地址:http://www.cnblogs.com/chevin/p/5673033.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!