go - Golang: file.Seek and file.WriteAt not working as expected -


i trying make program writes @ provided offsets in file, can start writing 20th offset etc.

here 1 of sample code using reference

package main  import (     "fmt"     "io/ioutil"     "os" )  const (     filename   = "sample.txt"     start_data = "12345" )  func printcontents() {     data, err := ioutil.readfile(filename)     if err != nil {         panic(err)     }     fmt.println("contents:", string(data)) }  func main() {     err := ioutil.writefile(filename, []byte(start_data), 0644)     if err != nil {         panic(err)     }      printcontents()      f, err := os.openfile(filename, os.o_rdwr, 0644)     if err != nil {         panic(err)     }     defer f.close()      if _, err := f.seek(20, 0); err != nil {         panic(err)     }      if _, err := f.writeat([]byte("a"), 15); err != nil {         panic(err)     }      printcontents() } 

but getting same file content beginning start like

12345a 

i tried changing seek values (0,0) , (20,0) , (10,1) randomly results in same output

also tried changing writeat offset other offset 10, 20 resulted in same.

i want solution can write @ specified position in file, suggest me wrong in code.

it works expected.

after running code, "sample.txt" file content (16 bytes):

[49 50 51 52 53 0 0 0 0 0 0 0 0 0 0 65] 

try:

package main  import (     "fmt"     "io/ioutil" )  const (     filename   = "sample.txt"     start_data = "12345" )  func printcontents() {     data, err := ioutil.readfile(filename)     if err != nil {         panic(err)     }     fmt.println(data) }  func main() {     printcontents() } 

you need write enough bytes first, use writeat offset:
e.g. edit :

start_data = "1234567890123456789012345678901234567890" 

then test code:

package main  import (     "fmt"     "io/ioutil"     "os" )  const (     filename   = "sample.txt"     start_data = "1234567890123456789012345678901234567890" )  func printcontents() {     data, err := ioutil.readfile(filename)     if err != nil {         panic(err)     }     fmt.println(string(data)) }  func main() {     err := ioutil.writefile(filename, []byte(start_data), 0644)     if err != nil {         panic(err)     }      printcontents()      f, err := os.openfile(filename, os.o_rdwr, 0644)     if err != nil {         panic(err)     }     defer f.close()      if _, err := f.seek(20, 0); err != nil {         panic(err)     }      if _, err := f.writeat([]byte("a"), 15); err != nil {         panic(err)     }      printcontents() } 

output:

1234567890123456789012345678901234567890 123456789012345a789012345678901234567890 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -