Go os and bufio

The os and bufio packages are extremely important in the Go language, primarily used for handling file systems and I/O operations.

os package

The os package provides basic functionalities for interacting with the operating system, including file operations, environment variables, system calls, and more.

Standard Input/Output in the os Package

The terminal is essentially a file, hence it possesses relevant file operation functionalities:

  1. os.Stdin:An instance of the file for standard input
  2. os.Stdout:An instance of the file for standard output
  3. os.Stderr:An instance of the file for standard error output
buf := make([]byte, 1024)
os.Stdin.Read(buf)
os.Stdout.WriteString(string(buf))

File Operations in the os Package

FileModeMeaning
os.O_CREATECreate a file
os.O_RDONLYRead-only
os.O_WRONLYWrite-only
os.O_RDWRRead and write
os.O_TRUNCClear file content
os.O_APPENDAppend content

There are numerous interfaces related to file operations, but the commonly used ones are:

  1. func Open(name string) (*File, error),Opens a file in read-only mode
  2. func Create(name string) (*File, error),Creates a file for reading and writing. If the file already exists, it is truncated
  3. func OpenFile(name string, flag int, perm FileMode),Opens or creates a file with specified flags and permissions
  4. func (f *File) Read(b []byte) (n int, err error),Reads file content into the slice b
  5. func (f *File) Write(b []byte) (n int, err error),Writes the slice b into the file
  6. func (f *File) WriteString(s string) (n int, err error),Writes the string s into the file
    fileOpen, err := os.Open("/tmp/log.txt")
    if err != nil {
        fmt.Println("open file failed!, err:", err)
        return
    }
    defer fileOpen.Close()
    
    buf := make([]byte, 1024)
    content := []byte{}
    for {
        n, err := fileOpen.Read(buf)
        if (err != nil) || (err == io.EOF) {
            break
        }
        content = append(content, buf[:n]...)
    }
    
    fileCreate, err := os.Create("/tmp/restore.txt")
    if err != nil {
        fmt.Println("failed to create file: %v", err)
        return
    }
    /*
        //If you want to append content
        fileCreate, err := os.OpenFile("/tmp/restore.txt", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
        if err != nil {
            log.Fatalf("failed to open file: %v", err)
        }
    */
    defer fileCreate.Close()
    
    if len(content) > 0 {
        fileCreate.Write(content)
        //fileCreate.WriteString(string(content))
    }

Directory Operations in the os Package

There are also several interfaces related to directory operations, commonly used ones include:

  1. func Getwd() (dir string, err error),Retrieves the current working directory
  2. func IsNotExist(err error) bool,Determines if an error indicates that a file or directory does not exist
  3. func IsExist(err error),Determines if an error indicates that a file or directory already exists
  4. func MkdirAll(path string, perm FileMode),Creates a directory along with all necessary parent directories
  5. func Mkdir(name string, perm FileMode),Creates a new directory
//If the directory does not exist, it will be created
if _, err := os.Stat(dir); os.IsNotExist(err) {
    err = os.MkdirAll(dir, 0777)
    if err != nil {
        fmt.Printf("failed to create dir '%s':%v", dir, err)
    }
    fmt.Printf("dir '%s' created success\n", dir)
}

bufio Package

The bufio package implements buffered I/O operations, which are typically faster than unbuffered I/O due to reduced system calls. Some commonly used interfaces include:

  1. func NewReader(rd io.Reader) *Reader,Creates a new buffered reader
  2. func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error),Reads a line, excluding "\r\n" or "\n"
  3. func (b *Reader) ReadString(delim byte) (string, error),Reads characters until a specified delimiter or EOF is encountered
  4. func NewWriter(w io.Writer) *Writer,Creates a new buffered writer
  5. func (b *Writer) WriteString(s string) (int, error),Writes a string to the buffer
  6. func (b *Writer) Flush() error,Flushes the buffer's contents to the file
func main() {
    fileOpen, err := os.Open("/tmp/log.txt")
    if err != nil {
        return
    }
    defer fileOpen.Close()
    
    var content string
    reader := bufio.NewReader(fileOpen)
    for {
        line, _, err := reader.ReadLine()
        if err == io.EOF {
            break
        }
        if err != nil {
            break
        }
        content += string(line) + "\r\n"
    }
    
    fileCreate, err := os.Create("/tmp/restore.txt")
    if err != nil {
        return
    }
    defer fileCreate.Close()
    
    writer := bufio.NewWriter(fileCreate)
    defer writer.Flush()
    
    _, err = writer.WriteString(content)
    if err != nil {
        return
    }
}

 

Take a break

👉👉👉 【Jade Dynasty EP46】An exciting confrontation between two beauties: Lu Xueqi vs Jin Ping'er