Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

System-related operations

os

The OS package provides the Create, NewFile, Open, OpenFile, and Remove methods

File object that provides Read and Write methods, such as Write, WriteAt, WriteString, Read, and ReadAt methods

File open and close
package main

import (
    "fmt"
    "os"
)

func main(a) {
    // Open the main.go file in the current directory in read-only mode
    file, err := os.Open("./main.go")
    iferr ! =nil {
        fmt.Println("open file failed! , err:", err)
        return
    }
    // Close the file
    file.Close()
}
Copy the code

Golang can consider simplifying file opening and exception handling and closing. Python’s with Open simplifies the handling of try and close exceptions, making the code more concise. Writers don’t have to worry about exception handling and file closing code, which is not business logic code, and the tendency is to let the language or machine do it automatically

Write files
file.WriteString("ab\n")
file.Write([]byte("cd\n")

Copy the code
Read the file

Golang files can be Read with file.read () and file.readat (). Reading at the end of the file returns an error with io.eof, which is the end identifier for reading in most languages

Golang OS package also need to read and write partial upper encapsulation, don’t let the developers to understand the principle of so much reading and writing, such as reading a line, the entire file, these are the developers prefer to use, need not care about the principle of read and write, as for property developers to think is to solve the problem of language, of course, when we have enough experience, You can use a lower level approach to improve performance. If hardware is moving faster, we want people to be able to use the higher-level approach without worrying about the underlying implementation

package main

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

func main(a) {
    // Open the file
    file, err := os.Open("./xxx.txt")
    iferr ! =nil {
        fmt.Println("open file err :", err)
        return
    }
    defer file.Close()
    // Define an array of bytes to receive file reads
    var buf [128]byte
    var content []byte
    for {
        n, err := file.Read(buf[:])
        if err == io.EOF {
            // Finish reading
            break
        }
        iferr ! =nil {
            fmt.Println("read file err ", err)
            return
        }
        content = append(content, buf[:n]...)
    }
    fmt.Println(string(content))
}
Copy the code