doucheng4094 2018-10-04 21:42
浏览 81
已采纳

写入文件,然后立即将其读回

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
"
_, 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.

  • 写回答

1条回答 默认 最新

  • douhao2721 2018-10-04 21:56
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题