Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

affected/package: os #50845

Closed
athxx opened this issue Jan 27, 2022 · 2 comments
Closed

affected/package: os #50845

athxx opened this issue Jan 27, 2022 · 2 comments

Comments

@athxx
Copy link

athxx commented Jan 27, 2022

$ go version 1.17.6

Does this issue reproduce with the latest release?

yes

What operating system and processor architecture are you using (go env)?

go env Output
set GO111MODULE=on
set GOARCH=amd64
set GOBIN=D:\Apps\gowin\bin
set GOCACHE=C:\Users\Administrator\AppData\Local\go-build
set GOENV=C:\Users\Administrator\AppData\Roaming\go\env
set GOEXE=.exe
set GOEXPERIMENT=
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOINSECURE=
set GOMODCACHE=E:\Dev\gopath\pkg\mod
set GONOPROXY=
set GONOSUMDB=
set GOOS=windows
set GOPATH=E:\Dev\gopath
set GOPRIVATE=
set GOPROXY=https://goproxy.io,direct
set GOROOT=D:\Apps\gowin
set GOSUMDB=sum.golang.org
set GOTMPDIR=
set GOTOOLDIR=D:\Apps\gowin\pkg\tool\windows_amd64
set GOVCS=
set GOVERSION=go1.17.6
set GCCGO=gccgo
set AR=ar
set CC=gcc
set CXX=g++
set CGO_ENABLED=1
set GOMOD=E:\Dev\go\slm\svr\go.mod
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config
set GOGCCFLAGS=-m64 -mthreads -fmessage-length=0 -fdebug-prefix-map=C:\Users\ADMINI~1\AppData\Local\Temp\go-build2452781041=/tmp/go-build -gno-record-gcc-switches

What did you do?

I run this code times, when I try to run more than twice, it will leave many NUL characters in the document

package main
func main() {
	fPath := "./test.txt"
	f, _ := os.OpenFile(fPath, os.O_CREATE|os.O_RDWR, os.ModePerm)
	stat, _ := f.Stat()
	buf := make([]byte, stat.Size())
	f.Read(buf)
	f.Truncate(0)
	f.Sync()
	fmt.Println(string(buf))
	for i := 0; i < 10; i++ {
		f.WriteString(time.Now().GoString() + "\n")
	}
}

What did you expect to see?

it cleans all content and inserts new content

What did you see instead?

it remains many NUL characters

@ianlancetaylor
Copy link
Member

I think that you are assuming that f.Truncate(0) resets the I/O position of the file to zero. It does not. After f.Truncate add a call to f.Seek(0, io.SeekStart). Then I think you will see the behavior that you expect.

@athxx
Copy link
Author

athxx commented Jan 27, 2022

@ianlancetaylor thanks

@golang golang locked and limited conversation to collaborators Jan 27, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants