Skip to content

Instantly share code, notes, and snippets.

@limboinf
Created May 26, 2016 02:35
Show Gist options
  • Save limboinf/1ffd300517a3b7a5c3e50e0697ed3fa2 to your computer and use it in GitHub Desktop.
Save limboinf/1ffd300517a3b7a5c3e50e0697ed3fa2 to your computer and use it in GitHub Desktop.
golang print file content
//打印文件内容
package main
import (
"bufio"
"bytes"
"fmt"
"os"
"io"
"path/filepath"
)
func main() {
path := "hello.go"
ba ,err := readFile(path)
if err != nil {
fmt.Println("Error: %s\n", err)
}
fmt.Printf("The content of '%s' : \n%s\n", path, ba)
}
func readFile(path string) ([]byte, error) {
parentPath, err := os.Getwd()
if err != nil {
return nil, err
}
pullPath := filepath.Join(parentPath, path)
file, err := os.Open(pullPath)
if err != nil {
return nil, err
}
defer file.Close()
return read(file)
}
func read(fd_r io.Reader) ([]byte, error) {
br := bufio.NewReader(fd_r)
var buf bytes.Buffer
for {
ba, isPrefix, err := br.ReadLine()
if err != nil {
if err == io.EOF {
break
}
return nil, err
}
buf.Write(ba)
if !isPrefix {
buf.WriteByte('\n')
}
}
return buf.Bytes(), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment