How to perform byte-level I/O operations (e.g., reading/writing individual bytes) in Go?

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:

  1. Open the file using os.Open to get a file handle.
  2. Create a buffer of size 1 byte.
  3. Use the Read method of the file handle to read bytes into the buffer.
  4. Handle the returned error if any.
  5. Process the byte read from 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:

  1. Open the file using os.Create to get a file handle.
  2. Write the byte(s) to the file handle using the Write method.
  3. Handle the returned error if any.
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.