如何在Tar目录中获取tar文件所需的路径
问题描述:
我一直在使用此代码写入tar文件。我称它为 err = retarIt(dirTopDebug, path)
,其中dirTopDebug
是我的tar文件(/tmp/abc.tar
)的路径,而path
是我要添加的文件的路径(/tmp/xyz/...
)。当我解压生成的tar文件时,我发现里面的abc.tar
文件都是/tmp/xyz/..
的格式。但我希望它们在tar内如xyz/...
,即没有tmp
文件夹。如何在Tar目录中获取tar文件所需的路径
我该怎么做?
func TarGzWrite(_path string, tw *tar.Writer, fi os.FileInfo) {
fr, _ := os.Open(_path)
//handleError(err)
defer fr.Close()
h := new(tar.Header)
h.Name = _path
h.Size = fi.Size()
h.Mode = int64(fi.Mode())
h.ModTime = fi.ModTime()
err := tw.WriteHeader(h)
if err != nil {
panic(err)
}
_, _ = io.Copy(tw, fr)
//handleError(err)
}
func IterDirectory(dirPath string, tw *tar.Writer) {
dir, _ := os.Open(dirPath)
//handleError(err)
defer dir.Close()
fis, _ := dir.Readdir(0)
//handleError(err)
for _, fi := range fis {
fmt.Println(dirPath)
curPath := dirPath + "/" + fi.Name()
if fi.IsDir() {
//TarGzWrite(curPath, tw, fi)
IterDirectory(curPath, tw)
} else {
fmt.Printf("adding... %s\n", curPath)
TarGzWrite(curPath, tw, fi)
}
}
}
func retarIt(outFilePath, inPath string) error {
fw, err := os.Create(outFilePath)
if err != nil {
return err
}
defer fw.Close()
gw := gzip.NewWriter(fw)
defer gw.Close()
// tar write
tw := tar.NewWriter(gw)
defer tw.Close()
IterDirectory(inPath, tw)
fmt.Println("tar.gz ok")
return nil
}
答
无论在tar头中指定了什么名字,都会使用。使用字符串包的strings.LastIndex(或strings.Index)函数将部分分隔到/ tmp。因此,如果上述TarGzWrite函数中的代码被修改如下,它将以您想要的方式工作(注意:您可能需要用strings.Index替换下面的strings.LastIndex)。
//TarGzWrite function same as above....
h := new(tar.Header)
//New code after this..
lastIndex := strings.LastIndex(_path, "/tmp")
fmt.Println("String is ", _path, "Last index is", lastIndex)
var name string
if lastIndex > 0 {
name = _path[lastIndex+len("/tmp")+1:]
fmt.Println("Got name:", name)
} else {
//This would not be needed, but was there just for testing my code
name = _path
}
// h.Name = _path
h.Name = name
h.Size = fi.Size()
h.Mode = int64(fi.Mode())