Go的os.Truncate()函数不会重置文件指针。

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

Go os.Truncate() not resetting the file cursor

问题

我最近尝试使用os.Truncate函数,参数为0,以清空文件的内容,然后将修改后的版本重新写入文件(我知道这是一种非常不安全的做法,但文件的内容对我来说并不重要)。

让我震惊的是,Truncate函数并没有重置文件的光标,所以当我重新写入文件时,文件前面会有一堆空字节(对应于先前内容的大小),除非我在此之前使用file.Seek(0, 0)

所以我的问题是:这是语言的一个bug吗?在实现该函数时是否遗漏了某些内容?还是故意这样设计的,出于某种神秘的原因,这是一种期望的行为?可能的神秘原因是什么?

我正在使用go版本go1.3.3 linux/amd64。

英文:

I recently tried to use os.Truncate with a parameter of 0 to clear a file's contents before rewritting a modified version into it (I know that it is a very unsafe practice, but the file's contents are not important to me).

The thing that shocked me is that Truncate did not reset the file's cursor, so when I wrote back to the file I ended up with a file prefixed with a bunch of null bytes (corresponding to the size of the previous contents), unless I used file.Seek(0, 0) beforehand.

So my question is: is that a bug of the language, something that was forgotten during the implementation of that function, or is it on purpose and it is a desired behaviour for some mysterious reason ? What could possibly be that mysterious reason ?

I'm using go version go1.3.3 linux/amd64

答案1

得分: 6

这是期望的行为:Go语言的实现模仿了C语言的工作方式。根据[ftruncate(2)]的man页面:

文件偏移量不会改变。

*技术上来说,这是因为Go语言的实现执行了ftruncate(2)系统调用

英文:

This is desired behaviour: the Go implementation mimics how the C works*. From the man page for ftruncate(2):

> The file offset is not changed.

* Technically, this is because the Go implementation executes the ftruncate(2) syscall.

huangapple
  • 本文由 发表于 2015年9月5日 18:49:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/32412194.html
匿名

发表评论

匿名网友

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

确定