Reading files
suggest changeRead the whole file
The simplest way to read a whole file is:
d, err := ioutil.ReadFile("foo.txt")
if err != nil {
log.Fatalf("ioutil.ReadFile failed with '%s'\n", err)
}
fmt.Printf("Size of 'foo.txt': %d bytes\n", len(d))
Open file for reading, close file
f, err := os.Open("foo.txt")
if err != nil {
log.Fatalf("os.Open failed with '%s'\n", err)
}
defer f.Close()
Open returns *os.File
which implements io.Reader
and io.Closer
interfaces.
You should always close files to avoid leaking file descriptors. defer
is perfect for ensuring Close
will be called on exit of the function.
Read file line by line
// ReadLines reads all lines from a file
func ReadLines(filePath string) ([]string, error) {
file, err := os.OpenFile(filePath, os.O_RDONLY, 0666)
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
res := make([]string, 0)
for scanner.Scan() {
line := scanner.Text()
res = append(res, line)
}
if err = scanner.Err(); err != nil {
return nil, err
}
return res, nil
}
func main() {
path := "main.go"
lines, err := ReadLines(path)
if err != nil {
log.Fatalf("ReadLines failed with '%s'\n", err)
}
fmt.Printf("File %s has %d lines\n", path, len(lines))
}
File main.go has 41 lines
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents