Go 学习之终端与文件读写 (四)

一、终端读写

1、终端读写

操作终端相关文件句柄常量

  • os.Stdin:标准输入
  • os.Stdout:标准输出
  • os.Stderr:标准错误输出

2、终端读写示例

package main

import (
    "fmt"
)

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

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

3、带缓冲区的读写

package main

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

var inputReader *bufio.Reader
var input string
var err error

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

二、文件读写

os.File封装所有文件相关操作,之前讲的 os.Stdin,os.Stdout, os.Stderr都是 *os.File

  • a、打开一个文件进行读操作:os.Open(name string) (*File, error)
  • b、关闭一个文件:File.Close()

文件操作示例

package main

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

func main() {

    inputFile, err := os.Open("input.dat")
    if err != nil {
        fmt.Printf("open file err:%v\n", err)
        return
    }

    defer inputFile.Close()
    inputReader := bufio.NewReader(inputFile)
    for {
        inputString, readerError := inputReader.ReadString('\n')
        if readerError == io.EOF {
            return
        }
        fmt.Printf("The input was: %s", inputString)
    }
}

读取整个文件示例

package main

import (
    "fmt"
    "io/ioutil"
    "os"
)

func main() {

    inputFile := "products.txt"
    outputFile := "products_copy.txt"
    buf, err := ioutil.ReadFile(inputFile)
    if err != nil {
        fmt.Fprintf(os.Stderr, "File Error: %s\n", err)
        return
    }

    fmt.Printf("%s\n", string(buf))
    err = ioutil.WriteFile(outputFile, buf, 0x644)
    if err != nil {
        panic(err.Error())
    }
}

读取压缩文件示例

package main

import (
    "bufio"
    "compress/gzip"
    "fmt"
    "os"
)
func main() {
    fName := "MyFile.gz"
    var r *bufio.Reader
    fi, err := os.Open(fName)
    if err != nil {
        fmt.Fprintf(os.Stderr, "%v, Can’t open %s: error: %s\n", os.Args[0], fName, err)
        os.Exit(1)
    }
    fz, err := gzip.NewReader(fi)
    if err != nil {
        fmt.Fprintf(os.Stderr, "open gzip failed, err: %v\n", err)
        return
    }
    r = bufio.NewReader(fz)
    for {
        line, err := r.ReadString('\n')
        if err != nil {
            fmt.Println("Done reading file")
            os.Exit(0)
        }
        fmt.Println(line)
    }
}

文件写入

file

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

拷贝文件

package main

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

func main() {

    CopyFile("target.txt", "source.txt")
    fmt.Println("Copy done!")
}

func CopyFile(dstName, srcName string) (written int64, err error) {
    src, err := os.Open(srcName)
    if err != nil {
        return
    }
    defer src.Close()
    dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
    if err != nil {
        return
    }
    defer dst.Close()
    return io.Copy(dst, src)
}

os.Args参数

os.Args是一个string的切片,用来存储所有的命令行参数。

带缓冲区的文件读写

package main

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

func cat(r *bufio.Reader) {
    for {
        buf, err := r.ReadBytes('\n')
        if err == io.EOF {
            break
        }
        fmt.Fprintf(os.Stdout, "%s", buf)

        return
    }
}

func main() {
    flag.Parse()
    if flag.NArg() == 0 {
        cat(bufio.NewReader(os.Stdin))
    }
    for i := 0; i < flag.NArg(); i++ {
        f, err := os.Open(flag.Arg(i))
        if err != nil {
            fmt.Fprintf(os.Stderr, "%s:error reading from %s: %s\n",
                os.Args[0], flag.Arg(i), err.Error())
        }
        continue
    }
    cat(bufio.NewReader(f))
}

为者常成,行者常至