如何截断并完全重写一个文件,而不会有前导零?

huangapple go评论79阅读模式
英文:

How do I truncate and completely rewrite a file without having leading zeros?

问题

当截断文件时,似乎会在开头添加额外的零字节:

configFile, err := os.OpenFile("./version.json", os.O_RDWR, 0666)
defer configFile.Close()
check(err)
//一些操作在这里发生
configFile.Truncate(0)
configFile.Write(js)
configFile.Sync()

结果是文件的内容是我写入的内容,但开头有一段0字节。

如何在没有前导零的情况下截断并完全重写文件?

英文:

When truncating a file it seems to be adding additional zero bytes to the start:

configFile, err := os.OpenFile("./version.json", os.O_RDWR, 0666)
defer configFile.Close()
check(err)
//some actions happen here
configFile.Truncate(0)
configFile.Write(js)
configFile.Sync()

As a result the file has the contents I write with a section of 0 bytes at the beginning.

How do I truncate and completely rewrite a file without having leading zeros?

答案1

得分: 43

请参考Truncate的文档

> Truncate函数用于改变文件的大小,但不会改变I/O偏移量。如果发生错误,将会返回PathError类型的错误。

因此,在写入之前,您还需要将文件的偏移量定位到文件的开头:

configFile.Truncate(0)
configFile.Seek(0, 0)

作为简写,可以在调用os.OpenFile时使用标志os.O_TRUNC来在打开文件时进行截断。

英文:

See the documentation on Truncate:

> Truncate changes the size of the file. It does not change the I/O offset. If there is an error, it will be of type *PathError.

So you also need to seek to the beginning of the file before you write:

configFile.Truncate(0)
configFile.Seek(0,0)

As shorthand, use the flag os.O_TRUNC when calling os.OpenFile to truncate on open.

答案2

得分: 2

我想展示一种在你只想截断文件的情况下的替代方案,可以考虑以下选项:

func truncate(filename string, perm os.FileMode) error {
    f, err := os.OpenFile(filename, os.O_TRUNC, perm)
    if err != nil {
        return fmt.Errorf("无法打开文件 %q 进行截断:%v", filename, err)
    }
    if err = f.Close(); err != nil {
        return fmt.Errorf("截断文件 %q 后无法关闭文件句柄:%v", filename, err)
    }
    return nil
}

这段代码使用了Go语言,通过打开文件并使用os.O_TRUNC标志来截断文件。如果打开文件或关闭文件句柄时出现错误,将返回相应的错误信息。

英文:

I'd like to show an alternative for cases where you may just want to truncate the file, then another option may be the following:

<!-- golang -->

func truncate(filename string, perm os.FileMode) error {
	f, err := os.OpenFile(filename, os.O_TRUNC, perm)
	if err != nil {
		return fmt.Errorf(&quot;could not open file %q for truncation: %v&quot;, filename, err)
	}
	if err = f.Close(); err != nil {
		return fmt.Errorf(&quot;could not close file handler for %q after truncation: %v&quot;, filename, err)
	}
	return nil
}

huangapple
  • 本文由 发表于 2017年6月7日 23:15:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/44416645.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定