How to Read File in Go: Simple Guide with Examples
In Go, you can read a file using
os.ReadFile which returns the file content as bytes and an error. Alternatively, use os.Open to open a file and then read it with a buffer or io.ReadAll.Syntax
The simplest way to read a whole file at once is using os.ReadFile. It takes the file path as a string and returns the file content as a byte slice and an error if any.
Example syntax:
data, err := os.ReadFile("filename.txt")Here, data holds the file bytes, and err should be checked for errors like file not found.
go
data, err := os.ReadFile("filename.txt") if err != nil { // handle error } // use data
Example
This example reads a file named example.txt and prints its content as a string. It shows how to handle errors properly.
go
package main import ( "fmt" "os" ) func main() { data, err := os.ReadFile("example.txt") if err != nil { fmt.Println("Error reading file:", err) return } fmt.Println(string(data)) }
Output
Hello, Go file reading!
Common Pitfalls
- Not checking the error returned by
os.ReadFilecan cause your program to crash or behave unexpectedly. - Trying to read very large files at once may consume too much memory; consider reading in chunks with
os.Openand a buffer. - Using the wrong file path or missing file permissions will cause errors.
go
package main import ( "fmt" "os" ) func main() { // Wrong way: ignoring error data, _ := os.ReadFile("missing.txt") fmt.Println(string(data)) // May print empty or cause confusion // Right way: check error data, err := os.ReadFile("missing.txt") if err != nil { fmt.Println("Failed to read file:", err) return } fmt.Println(string(data)) }
Output
Failed to read file: open missing.txt: no such file or directory
Quick Reference
| Function | Description |
|---|---|
| os.ReadFile(path string) | Reads entire file content into memory |
| os.Open(path string) | Opens file for reading, returns *File |
| file.Read(buffer []byte) | Reads bytes into buffer from opened file |
| io.ReadAll(reader io.Reader) | Reads all data from reader into bytes |
Key Takeaways
Use os.ReadFile for simple, whole-file reading with error checking.
Always check errors returned when reading files to avoid crashes.
For large files, open and read in chunks instead of reading all at once.
File paths and permissions must be correct to successfully read files.
Use io.ReadAll with os.Open for more controlled reading scenarios.