In Go, you can perform byte-level I/O operations using the io
package. Here's how you can read and write individual bytes:
Reading individual bytes from a file:
os.Open
to get a file handle.Read
method of the file handle to read bytes into the buffer.file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
buffer := make([]byte, 1)
for {
_, err := file.Read(buffer)
if err != nil {
if err == io.EOF {
break // Reached end of file
}
log.Fatal(err)
}
// Process the byte read from the buffer
fmt.Println(buffer[0])
}
Writing individual bytes to a file:
os.Create
to get a file handle.Write
method.file, err := os.Create("file.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
byteToWrite := byte(65) // Example byte to write
buffer := []byte{byteToWrite}
_, err = file.Write(buffer)
if err != nil {
log.Fatal(err)
}
Note: In the above examples, proper error handling and file closing using defer
statements have been shown for simplicity.