douzhao4071
2015-12-22 15:29
浏览 35
已采纳

golang zlib阅读器输出未复制到stdout

I've modified the official documentation example for the zlib package to use an opened file rather than a set of hardcoded bytes (code below).

The code reads in the contents of a source text file and compresses it with the zlib package. I then try to read back the compressed file and print its decompressed contents into stdout.

The code doesn't error, but it also doesn't do what I expect it to do; which is to display the decompressed file contents into stdout.

Also: is there another way of displaying this information, rather than using io.Copy?

    package main

    import (
        "compress/zlib"
        "io"
        "log"
        "os"
    )

    func main() {
        var err error

        // This defends against an error preventing `defer` from being called
        // As log.Fatal otherwise calls `os.Exit`
        defer func() {
            if err != nil {
                log.Fatalln("
Deferred log: 
", err)
            }
        }()

        src, err := os.Open("source.txt")
        if err != nil {
            return
        }
        defer src.Close()

        dest, err := os.Create("new.txt")
        if err != nil {
            return
        }
        defer dest.Close()

        zdest := zlib.NewWriter(dest)
        defer zdest.Close()

        if _, err := io.Copy(zdest, src); err != nil {
            return
        }

        n, err := os.Open("new.txt")
        if err != nil {
            return
        }

        r, err := zlib.NewReader(n)
        if err != nil {
            return
        }
        defer r.Close()
        io.Copy(os.Stdout, r)

        err = os.Remove("new.txt")
        if err != nil {
            return
        }
    }

图片转代码服务由CSDN问答提供 功能建议

我修改了zlib软件包的官方文档示例,以使用打开的文件而不是一组硬编码的字节 (下面的代码)。

该代码读取源文本文件的内容,并使用zlib软件包对其进行压缩。 然后,我尝试读回压缩文件,并将其解压缩后的内容打印到stdout中。

代码没有错误,但是也没有达到我的预期。 将解压缩的文件内容显示为stdout。

另外:还有另一种显示此信息的方法,而不是使用 io.Copy

 包main 
 
导入(
“ compress / zlib” 
“ io” 
“ log” 
“ os” 
)
 
 func main  (){
 var err error 
 
 //这可以防止防止调用`defer`的错误
 //作为log.Fatal否则调用`os.Exit` 
 defer func(){
 如果err!= nil {
 log.Fatalln(“ 
Deferred log:
”,err)
} 
}()
 
 src,err:= os.Open(“ source.txt”)  
 if err!= nil {
 return 
} 
延迟src.Close()
 
 dest,err:= os.Create(“ new.txt”)
 if err!= nil {\  n return 
} 
延迟dest.Close()
 
 zdest:= zlib.NewWriter(dest)
延迟zdest.Close()
 
如果_,err:= io.Copy(zdest,  SRC);  err!= nil {
 return 
} 
 
n,err:= os.Open(“ new.txt”)
如果err!= nil {
 return 
} 
 
r,err:  = zlib.NewReader(n)
,如果出错!= nil {
 return 
} 
延迟r.Close()
 io.Copy(os.Stdout,r)
 
 err = os.Remove  (“ new.txt”)
,如果错误!= nil {
 return 
} 
} 
   
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

4条回答 默认 最新

相关推荐 更多相似问题