Search code examples
filegoio

Writing to File then immediately read it back in go


As the Title says, I have an issue with reading back a file I have written to just before the read. The read panics with EOF. I debugged into the various go internals, and it seems that for some reason it can not read any content from the source, although the source has been synched to the file system (confirmed by stopping the program just after the write and inspecting the file with cat)

Here is the code

source, err := os.Create(DESKTOP + "/source.txt")
myPanic(err)

s := "Hello World\n"
_, err1 := source.Write([]byte(s))

myPanic(err1)
source.Sync()

buff := make([]byte, 56)
_, err2 := source.Read(buff)
myPanic(err2)e

As mentioned, source.Sync() has no effect but closing the file and reopening it resolves the issue.

The doc for os.Create() states the the file is created with O_RDWR, which suggests to me that it is OK to use the file that way. I think I missed something along the way.

Just for the sake of completeness: The example is not the original issue I encountered, just the simplest possible case I came up with after my research.

Initially I wanted to copy the source file with os.Copy which creates an empty destination file.


Solution

  • You're at the end of your file, so reading from there isn't going to return any new data. Seek to the start of your file:

    source.Seek(0, io.SeekStart)