Skip to content

Instantly share code, notes, and snippets.

@bbengfort
Last active September 11, 2018 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbengfort/19651cf1aa51ede8c85a0747edb478b3 to your computer and use it in GitHub Desktop.
Save bbengfort/19651cf1aa51ede8c85a0747edb478b3 to your computer and use it in GitHub Desktop.
Use the `WriteAt` specification to write to a file at offsets.
package main
import (
"log"
"os"
)
func main() {
var (
fobj *os.File
err error
)
if fobj, err = os.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0644); err != nil {
log.Fatal(err)
}
defer fobj.Close()
// Write 6 bytes at the beginning of the file
if _, err = fobj.WriteAt([]byte("abcdef"), 0); err != nil {
log.Fatal(err)
}
// Append 6 bytes at the end of the file
if _, err = fobj.WriteAt([]byte("ghijkl"), 6); err != nil {
log.Fatal(err)
}
// Write 4 bytes in the middle of the file
if _, err = fobj.WriteAt([]byte("AAAA"), 4); err != nil {
log.Fatal(err)
}
// Write 3 bytes far after the current data
if _, err = fobj.WriteAt([]byte("BBB"), 18); err != nil {
log.Fatal(err)
}
}
#!/usr/bin/env python3
import io
def write_data(fobj, data, offset):
"""
Writes data to the specified BytesIO fobj at the specified offset,
then returns the total length of the resulting fobj for comparison.
"""
fobj.seek(offset, io.SEEK_SET) # Go to the offset from the beginning of the file
fobj.write(data) # Write data to the fobj
# Return the length of the internal buffer
return len(fobj.getbuffer())
def p_write_data(fobj, data, offset):
"""
Executes write data and pretty prints the result for debugging
"""
length = write_data(fobj, data, offset)
print("write({: >10}, {:>2}) -> {:>3} {}".format(repr(data), offset, length, repr(fobj.getvalue())))
# Create empty file-object
fobj = io.BytesIO()
# Write 6 bytes at the beginning of the file
p_write_data(fobj, b'abcdef', 0)
# Append 6 bytes at the end of the file
p_write_data(fobj, b'ghijkl', 6)
# Write 4 bytes in the middle of the file
p_write_data(fobj, b'AAAA', 4)
# Write 3 bytes after the current data
p_write_data(fobj, b'BBB', 18)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment