Last active
September 11, 2018 13:34
-
-
Save bbengfort/19651cf1aa51ede8c85a0747edb478b3 to your computer and use it in GitHub Desktop.
Use the `WriteAt` specification to write to a file at offsets.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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