2020-03-09-golang-读取流操作

读取控制台输入

使用fmt.Sscanf

示例代码:

package main

import "fmt"

var (
    firstName string
    lastName  string
    s         string
    i         int
    f         float32
    input     = "56.12 / 5212 / Go"
    format    = "%f / %d / %s"
)

func main() {
    fmt.Println("Please input your name :")
    fmt.Scanln(&firstName, &lastName)
    fmt.Printf("Hi %s %s!\n", firstName, lastName)
    fmt.Sscanf(input, format, &f, &i, &s)
    fmt.Println("From the string we read: ", f, i, s)
}

文件的读写

示例1:读文件

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
)

func main() {
    inputFile, inputError := os.Open("./readinput1.go")
    if inputError != nil {
        fmt.Printf("An error occurred on opening the inputfile\n" +
            "Does the file exist?\n" +
            "Have you got acces to it?\n")
        return // exit the function on error
    }

    defer inputFile.Close() //为了防止忘记关闭流,使用了延迟函数
    inputReader := bufio.NewReader(inputFile)
    for {
        inputString, readerError := inputReader.ReadString('\n')
        fmt.Printf(inputString)
        if readerError == io.EOF { //判断结束字符
            return
        }
    }
}

示例2:写文件

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 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()
}