2017-04-12 2 views
0

私はこのコードを使ってtarファイルに書きました。 err = retarIt(dirTopDebug, path)のように、dirTopDebugはtarファイル(/tmp/abc.tar)へのパス、pathは追加したいファイルのパス(/tmp/xyz/...)です。生成されたtarファイルを解凍すると、abc.tarのファイルは/tmp/xyz/..という形式になります。しかし、tmpフォルダを使わずに、xyz/...のようにタールの中に入れておきたい。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 
} 

答えて

1

tarヘッダーに指定されている名前はすべて使用されます。文字列パッケージのstrings.LastIndex(またはstrings.Index)関数を使用して、/ tmpまでパートを区切ります。

したがって、上記のTarGzWrite関数のコードが以下のように変更された場合は、あなたが望むように動作します(注:strings.LastIndexをstrings.Indexに置き換えることもできます)。

//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()) 
関連する問題