why os.WriteAt not working?

604 views
Skip to first unread message

no1o...@gmail.com

unread,
Mar 10, 2014, 2:28:49 PM3/10/14
to golan...@googlegroups.com
hi there,

os.WriteAt seems could not write at the right place.

say a file with content "12345"

os.Seek(0, 0)
os.WriteAt("A", 2)

would output "12345A", i think it suppose to be "12A345"?

pls share me with the WHY?

thanks.

DV

unread,
Mar 10, 2014, 4:03:22 PM3/10/14
to golan...@googlegroups.com
Your code doesn't even compile. You sure you pasted the right version of it? 

This version - http://play.golang.org/p/UiZ6qScyq4 - works on my system (Windows x64) and does what you expect it to. 

Hope that helps. 

Carlos Castillo

unread,
Mar 10, 2014, 8:08:41 PM3/10/14
to golan...@googlegroups.com
Use the playground (http://play.golang.org) to post code examples. That way you can easily tell if you have written valid code (which you haven't).

Here is an example, that I think is what you want, which works in the playground (no need to download + build): http://play.golang.org/p/ZkGlmmswpr

Notes:
  • The os package doesn't have Seek, or WriteAt functions. The os.File type has methods with those names.
  • You have to use os.OpenFile if you want to modify an existing file, as os.Open only reads a file, and os.Create only creates a new file
  • Always check errors
  • WriteAt will *OVERWRITE* the contents from the given offset, so your expected result "12A345" is incorrect. It is not possible to insert characters in the middle of the file with the WriteAt or Write methods.

no1o...@gmail.com

unread,
Mar 10, 2014, 8:58:13 PM3/10/14
to golan...@googlegroups.com
Thanks for the hlep DV and Carlos. i think i found the reason. i opened the file with "os.O_RDWR|os.O_CREATE|os.O_APPEND)", so every time the cursor is set to the end of the file.
Reply all
Reply to author
Forward
0 new messages