Golang - write to file

Similar to Golang-reading files , Go can implement file writing operations through osor packages. ioutilWriting a file is generally done by returning a structure osthrough Openor a function , and then performing a write operation through the built-in function. The essence of adopting is also to use writing files, but it only makes a layer of encapsulation.CreateFileFileioutilos

Opens a file via os.Opena function, returning an error if the file does not exist.

Create a file through os.Createthe function, and clear the file content if the file already exists.

Writing files is based on []bytethe operations performed, and you need to understand stringand []byteconvert operations in advance.

b := []byte("ABC€")
fmt.Println(b) // [65 66 67 226 130 172]

s := string([]byte{
    
    65, 66, 67, 226, 130, 172})
fmt.Println(s) // ABC€

The following is a specific example, and the key codes have corresponding comments

package main

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

func main() {
    
    
	WriteByIoUtil("H:\\go\\main\\2.txt")
	WriteByOs("H:\\go\\main\\3.txt")
}

func WriteByIoUtil(filename string) {
    
    
	d := []byte("hello\ngo\n")
	err := ioutil.WriteFile(filename, d, 0644)
	CheckErr(err)
}

func WriteByOs(filename string)  {
    
    
	f, err := os.Create(filename)
	CheckErr(err)

	defer f.Close()

	//通过f.Write函数写文件
	d2 := []byte("some\n")
	n2, err := f.Write(d2)
	CheckErr(err)
	fmt.Printf("wrote %d bytes\n", n2)

	//通过f.WriteString函数写文件
	n3, err := f.WriteString("writes\n")
	CheckErr(err)
	fmt.Printf("wrote %d bytes\n", n3)
	f.Sync()

	//通过bufio提供的Writer.WriteString函数写文件
	w := bufio.NewWriter(f)
	n4, err := w.WriteString("buffered\n")
	CheckErr(err)
	fmt.Printf("wrote %d bytes\n", n4)
	w.Flush()
}

func CheckErr(e error) {
    
    
	if e != nil {
    
    
		panic(e)
	}
}

Guess you like

Origin blog.csdn.net/mryang125/article/details/114802728