Reputation: 1827
I am trying to make a program which writes at provided offsets in the file, like i can start writing from 20th offset etc.
here is one of sample code i was using as 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 i am always getting the same file content which is beginning from start like
12345A
I tried changing the seek values to (0,0) and (20,0) and (10,1) randomly which results in same output
Also i tried changing WriteAt offset to other offset like 10, 20 but this also resulted in same.
I want to get a solution so that i can write at any specified position in file, suggest me what is wrong in this code.
Upvotes: 2
Views: 11058
Reputation: 31
This is kind of a late answer, but it looks like that you can do something like this directly now.
You can directly use WriteAt
on a newly created os.File
at a non-zero offset.
https://go.dev/play/p/uOtS1LO2c1S
Upvotes: 1
Reputation:
It works as expected.
After running your code, your "sample.txt" file content is (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 to write enough bytes first, the use WriteAt offset:
e.g. edit :
start_data = "1234567890123456789012345678901234567890"
then test your 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
Upvotes: 6