英文:
Golang fails to write header to tar package?
问题
以下是代码的翻译:
fInfo, err := os.Stat(fp)
if err != nil {
fmt.Println(err.Error())
return
}
header, err := tar.FileInfoHeader(fInfo, "")
if err != nil {
fmt.Println(err.Error())
return
}
header.Name = name
if header.Format == tar.FormatUnknown {
header.Format = tar.FormatGNU
}
err = this.writer.WriteHeader(header)
if err != nil {
fmt.Println(err.Error())
return
}
f, err := os.Open(fp)
if err != nil {
fmt.Println(err.Error())
return
}
defer f.Close()
_, err = io.Copy(this.writer, f)
fmt.Println(err.Error())
return
报告了代码中的一个错误:
this.writer.WriteHeader(header)
错误信息如下:
archive/tar: missed writing 15251 bytes
我已经进行了多次测试,不知道为什么会出现这种错误。
需要注意的是,我打包的内容是U盘中的内容。
英文:
code show as below
fInfo, err := os.Stat(fp)
if err != nil {
fmt.Println(err.Error())
return
}
header, err := tar.FileInfoHeader(fInfo, "")
if err != nil {
fmt.Println(err.Error())
return
}
header.Name = name
if header.Format == tar.FormatUnknown {
header.Format = tar.FormatGNU
}
err = this.writer.WriteHeader(header)
if err != nil {
fmt.Println(err.Error())
return
}
f, err := os.Open(fp)
if err != nil {
fmt.Println(err.Error())
return
}
defer f.Close()
_, err = io.Copy(this.writer, f)
fmt.Println(err.Error())
return
Reporting an error in the diverted code
this.writer.WriteHeader(header)
The error is as follows
archive/tar: missed writing 15251 bytes
I have tested many times, I don't know why this error occurs in this way.
It should be noted that the content I packaged is the content in the U disk.
答案1
得分: 1
根据文档中的说明,WriteHeader 隐式调用 Flush,而 Flush 又会检查是否有剩余的字节数需要写入。如果有剩余的字节数需要写入,它将返回一个错误。
剩余的字节数存储在 nb
变量中,并在第一次写入头部时进行初始化。然后,每次写入一些内容时,nb
的值会减少已写入的字节数。
如果 nb
大于零,并且尝试第二次调用 WriteHeader
,你将会得到这个错误。
英文:
As it is mentioned in the documentation, WriteHeader implicitly calls Flush, which in turn checks is there any number of remaining bytes to write. If so it will return an error that you got.
The number of remaining bytes is stored in nb
variable and initialised when you write header first time. Then every time when you write some content it will be decreased by a number of bytes written.
If nb
is more then zero and you try to call WriteHeader
second time you will get this error.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论