Read the contents of a tar file without extracting to disk

王林
Release: 2024-02-09 22:27:21
forward
673 people have browsed it

读取 tar 文件的内容而不解压到磁盘

php editor Strawberry will introduce you to a very practical technique today - reading the contents of a tar file without decompressing it to disk. During the development process, we often need to process tar files, but decompressing them to disk and then reading them will take up a lot of disk space and time. By using PHP's Archive_Tar extension, we can directly read the contents of the tar file, avoid the tedious process of decompression, and improve the efficiency of the code. Next, let’s learn about the specific steps!

Question content

I have been able to loop through the files in a tar file, but I have never figured out how to read the contents of these files as a string. I want to know how to print the contents of a file as a string?

This is my code

package main

import (
    "archive/tar"
    "fmt"
    "io"
    "log"
    "os"
    "bytes"
    "compress/gzip"
)

func main() {
    file, err := os.Open("testtar.tar.gz")

    archive, err := gzip.NewReader(file)

    if err != nil {
        fmt.Println("There is a problem with os.Open")
    }
    tr := tar.NewReader(archive)

    for {
        hdr, err := tr.Next()
        if err == io.EOF {
            break
        }
        if err != nil {
            log.Fatal(err)
        }

        fmt.Printf("Contents of %s:\n", hdr.Name)
    }
}
Copy after login

Workaround

Just use tar.reader as the io.reader for each file you want to read.

tr := tar.newreader(r)

// get the next file entry 
h, _ := tr.next()
Copy after login

If you need the entire file as a string:

// read the complete content of the file h.name into the bs []byte
bs, _ := ioutil.readall(tr)

// convert the []byte to a string
s := string(bs)
Copy after login

If you need to read line by line, this is better:

// create a Scanner for reading line by line
s := bufio.NewScanner(tr)

// line reading loop
for s.Scan() {

  // read the current last read line of text
  l := s.Text()

  // ...and do something with l

}

// you should check for error at this point
if s.Err() != nil {
  // handle it
}
Copy after login

The above is the detailed content of Read the contents of a tar file without extracting to disk. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!