Last active
May 4, 2016 01:35
-
-
Save xigang/0f6f5bbb4083d2004e4f305e10dc1715 to your computer and use it in GitHub Desktop.
从文件中一样一行的读取文件
This file contains hidden or 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" | |
| "fmt" | |
| "log" | |
| "os" | |
| ) | |
| func main() { | |
| file, err := os.Open("/path/to/file.txt") | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| defer file.Close() | |
| scanner := bufio.NewScanner(file) | |
| for scanner.Scan() { | |
| fmt.Println(scanner.Text()) | |
| } | |
| if err := scanner.Err(); err != nil { | |
| log.Fatal(err) | |
| } | |
| } |
This file contains hidden or 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" | |
| "fmt" | |
| "os" | |
| ) | |
| func ReadLine(filename string) { | |
| f, err := os.Open(filename) | |
| if err != nil { | |
| fmt.Println(err) | |
| return | |
| } | |
| defer f.Close() | |
| r := bufio.NewReaderSize(f, 4*1024) | |
| line, isPrefix, err := r.ReadLine() | |
| for err == nil && !isPrefix { | |
| s := string(line) | |
| fmt.Println(s) | |
| line, isPrefix, err = r.ReadLine() | |
| } | |
| if isPrefix { | |
| fmt.Println("buffer size to small") | |
| return | |
| } | |
| if err != io.EOF { | |
| fmt.Println(err) | |
| return | |
| } | |
| } | |
| func ReadString(filename string) { | |
| f, err := os.Open(filename) | |
| if err != nil { | |
| fmt.Println(err) | |
| return | |
| } | |
| defer f.Close() | |
| r := bufio.NewReader(f) | |
| line, err := r.ReadString('\n') | |
| for err == nil { | |
| fmt.Print(line) | |
| line, err = r.ReadString('\n') | |
| } | |
| if err != io.EOF { | |
| fmt.Println(err) | |
| return | |
| } | |
| } | |
| func main() { | |
| filename := `testfile` | |
| ReadLine(filename) | |
| ReadString(filename) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment