Created
May 26, 2016 02:35
-
-
Save limboinf/1ffd300517a3b7a5c3e50e0697ed3fa2 to your computer and use it in GitHub Desktop.
golang print file content
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//打印文件内容 | |
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