Reading Files
This Go code demonstrates reading a file using various methods from the os
and io
packages. Let's go through the code with inline comments and explanations:
output
First make sure you have the dummy files on your working directory.
You might need to change some code for that.
Then run the
.go
file with the above code.
Explanation:
Reading Entire File:
os.ReadFile("/tmp/dat")
reads the entire contents of the file into a byte slice.
Reading Specific Bytes:
os.Open("/tmp/dat")
opens the file for further reading.f.Read(b1)
reads the first 5 bytes from the file.
Seeking and Reading:
f.Seek(6, 0)
seeks to the 6th byte in the file.f.Read(b2)
reads 2 bytes from the current position.
Seeking, Reading At Least, and Buffered Reading:
f.Seek(6, 0)
seeks to the 6th byte again.io.ReadAtLeast(f, b3, 2)
reads at least 2 bytes into a buffer.
Peeking with Buffered Reader:
bufio.NewReader(f)
creates a buffered reader.r4.Peek(5)
peeks at the first 5 bytes without consuming them.
Closing the File:
f.Close()
closes the file.
This code demonstrates various ways to read from a file in Go using different methods from the os
and io
packages.
Last updated