bufio
包提供的缓冲读取(buffered reader)来读取数据
package main
import (
"bufio"
"fmt"
"os"
)
var inputReader *bufio.Reader
func main() {
inputReader = bufio.NewReader(os.Stdin)
fmt.Println("please enter some input:")
input, err := inputReader.ReadString('\n')
if err == nil {
fmt.Printf("The input was: %s\n", input)
}
}
> go run main.go
please enter some input:
1111
The input was: 1111
读取文件
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func main() {
inputFile, inputError := os.Open("nginx.conf")
if inputError != nil {
fmt.Println("An error occurred on opening the inputfile", inputError)
return
}
defer inputFile.Close()
inputReader := bufio.NewReader(inputFile)
for {
inputString, readerError := inputReader.ReadString('\n')
fmt.Printf(inputString)
if readerError == io.EOF {
return
}
}
}
写入文件
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
outputFile, outputError := os.OpenFile("output.dat", os.O_WRONLY|os.O_CREATE, 0666)
if outputError != nil {
fmt.Printf("An error occurred with file opening or creating or creation \n")
return
}
defer outputFile.Close()
outputWriter := bufio.NewWriter(outputFile)
outputString := "hello world!!\n"
for i := 0; i < 10; i++ {
outputWriter.WriteString(outputString)
}
outputWriter.Flush()
}