Go basis of the language file operations

This paper describes the Go language related operations to read and write files.

What files are?

Computer files are stored in an external medium (usually disk) on the data collection file into text files and binary files.

Open and close the file

os.Open()Function to open a file, a return *Fileand a err. For instance obtained by calling the file close()method can close the file.

package main

import (
    "fmt"
    "os"
)

func main() {
    // 只读方式打开当前目录下的main.go文件
    file, err := os.Open("./main.go")
    if err != nil {
        fmt.Println("open file failed!, err:", err)
        return
    }
    // 关闭文件
    file.Close()
}

In order to prevent forgetting to close the file, we usually defer registration statement file is closed.

Read the file

file.Read()

Basic use

Read method is defined as follows:

func (f *File) Read(b []byte) (n int, err error)

It receives a byte slice, and returns the number of bytes read errors may be specific, when the end of file read returns 0and io.EOF. for example:

func main() {
    // 只读方式打开当前目录下的main.go文件
    file, err := os.Open("./main.go")
    if err != nil {
        fmt.Println("open file failed!, err:", err)
        return
    }
    defer file.Close()
    // 使用Read方法读取数据
    var tmp = make([]byte, 128)
    n, err := file.Read(tmp)
    if err == io.EOF {
        fmt.Println("文件读完了")
        return
    }
    if err != nil {
        fmt.Println("read file failed, err:", err)
        return
    }
    fmt.Printf("读取了%d字节数据\n", n)
    fmt.Println(string(tmp[:n]))
}

Read cycle

All the data for loop reads the file.

func main() {
    // 只读方式打开当前目录下的main.go文件
    file, err := os.Open("./main.go")
    if err != nil {
        fmt.Println("open file failed!, err:", err)
        return
    }
    defer file.Close()
    // 循环读取文件
    var content []byte
    var tmp = make([]byte, 128)
    for {
        n, err := file.Read(tmp)
        if err == io.EOF {
            fmt.Println("文件读完了")
            break
        }
        if err != nil {
            fmt.Println("read file failed, err:", err)
            return
        }
        content = append(content, tmp[:n]...)
    }
    fmt.Println(string(content))
}

bufio read the file

bufio API layer is encapsulated on the basis of the file, it supports more features.

package main

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

// bufio按行读取示例
func main() {
    file, err := os.Open("./main.go")
    if err != nil {
        fmt.Println("open file failed, err:", err)
        return
    }
    defer file.Close()
    reader := bufio.NewReader(file)
    for {
        line, err := reader.ReadString('\n') //注意是字符
        if err == io.EOF {
            fmt.Println("文件读完了")
            break
        }
        if err != nil {
            fmt.Println("read file failed, err:", err)
            return
        }
        fmt.Print(line)
    }
}

ioutil read the entire file

io/ioutilPacket ReadFilemethod can read the complete file, simply use a file name as an argument.

package main

import (
    "fmt"
    "io/ioutil"
)

// ioutil.ReadFile读取整个文件
func main() {
    content, err := ioutil.ReadFile("./main.go")
    if err != nil {
        fmt.Println("read file failed, err:", err)
        return
    }
    fmt.Println(string(content))
}

File write operations

os.OpenFile()Function can open the file in the specified mode, enabling file write-related functions.

func OpenFile(name string, flag int, perm FileMode) (*File, error) {
    ...
}

among them:

name: To open the file name flag: the file open mode. Mode are the following:

mode meaning
os.O_WRONLY just write
os.O_CREATE Create a file
os.O_RDONLY Read-only
os.O_RDWR Read and write
os.O_TRUNC Clear
os.O_APPEND add to

perm: File permissions, an octal number. r (read) 04, w (write) 02, x (execute) 01.

Write和WriteString

func main() {
    file, err := os.OpenFile("xx.txt", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
    if err != nil {
        fmt.Println("open file failed, err:", err)
        return
    }
    defer file.Close()
    str := "hello 沙河"
    file.Write([]byte(str))       //写入字节切片数据
    file.WriteString("hello 小王子") //直接写入字符串数据
}

bufio.NewWriter

func main() {
    file, err := os.OpenFile("xx.txt", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
    if err != nil {
        fmt.Println("open file failed, err:", err)
        return
    }
    defer file.Close()
    writer := bufio.NewWriter(file)
    for i := 0; i < 10; i++ {
        writer.WriteString("hello沙河\n") //将数据先写入缓存
    }
    writer.Flush() //将缓存中的内容写入文件
}

ioutil.WriteFile

func main() {
    str := "hello 沙河"
    err := ioutil.WriteFile("./xx.txt", []byte(str), 0666)
    if err != nil {
        fmt.Println("write file failed, err:", err)
        return
    }
}

Exercise

copyFile

With io.Copy()the realization of a file copy function.

// CopyFile 拷贝文件函数
func CopyFile(dstName, srcName string) (written int64, err error) {
    // 以读方式打开源文件
    src, err := os.Open(srcName)
    if err != nil {
        fmt.Printf("open %s failed, err:%v.\n", srcName, err)
        return
    }
    defer src.Close()
    // 以写|创建的方式打开目标文件
    dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
    if err != nil {
        fmt.Printf("open %s failed, err:%v.\n", dstName, err)
        return
    }
    defer dst.Close()
    return io.Copy(dst, src) //调用io.Copy()拷贝内容
}
func main() {
    _, err := CopyFile("dst.txt", "src.txt")
    if err != nil {
        fmt.Println("copy file failed, err:", err)
        return
    }
    fmt.Println("copy done!")
}

The realization of a cat command

Use file operations related knowledge, analog implementation linux platform catfunction commands.

package main

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

// cat命令实现
func cat(r *bufio.Reader) {
    for {
        buf, err := r.ReadBytes('\n') //注意是字符
        if err == io.EOF {
            break
        }
        fmt.Fprintf(os.Stdout, "%s", buf)
    }
}

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.Stdout, "reading from %s failed, err:%v\n", flag.Arg(i), err)
            continue
        }
        cat(bufio.NewReader(f))
    }
}

Guess you like

Origin www.cnblogs.com/nickchen121/p/11517429.html