Go language - file operation

catalogue

preface

1. Opening and closing files

2. Read file

3. Write file

preface

Files in a computer are data sets stored on external media (hard disk). Files are divided into text files and binary files.

1. Opening and closing files

os. The open() function can open a File and return a * File and an err. For the obtained File example, the close() method can close the File.

Example:

package main

import (
	"fmt"
	"os"
)

//Opening and closing of files
func main() {
	//Open ABC. In the current directory Txt file
	file, err := os.Open("./abc.txt")
	if err != nil {
		fmt.Println("File open failed", err)
	} else {
		fmt.Println("File opened successfully")
		file.Close()
		fmt.Println("File closed successfully")
	}
}

//The operation result is:
D:\goproject\src\dev_code\day25\demo1>go run main.go
 File opened successfully
 File closed successfully

2. Read file

Receive a byte slice, return the number of bytes read and possible specific errors, and return 0 and IO when reading to the end of the file EOF.

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

Example:

defer is generally used for resource release and exception capture.
The defer statement will delay the following statements; The language following defer will be executed after the final return of the program.
When the function to which defer belongs is about to return, the delayed statements are executed in the reverse order of defer, that is, the statements first deferred are executed last, and the statements last deferred are executed first.

package main

import "fmt"

func main() {
    //Delay processing, execute before the function is closed
	defer fmt.Println("implement defer sentence")
	for i := 0; i < 5; i++ {
		fmt.Println(i)
	}
}


//The output results are as follows
0
1
2
3
4
 implement defer sentence

Example:

package main

import "fmt"

func hello() {
	for i := 0; i < 10; i++ {
		fmt.Println(i)
		if i == 8 {
			break
		}
	}
	//Delay processing, execute before the function is closed
	defer fmt.Println("implement defer")
}
func main() {
	hello()
}

//The operation result is:
0
1
2
3
4
5
6
7
8
 implement defer

Example: open a file and get the content.

package main

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

//read file
func main() {
    //In the created ABC Txt file input content "hello world"
	file, err := os.Open("./abc.txt")
	if err != nil {
		fmt.Println("File open failed", err)
		return
	}
	//Execute file resource release before the end of main function
	defer file.Close()
	fmt.Println("File opened successfully")
	//Define parameter slice
	var result [128]byte
	n, err := file.Read(result[:])
	//File read complete
	if err == io.EOF {
		fmt.Println("File read complete", err)
		return
	}
	//An exception occurred during reading
	if err != nil {
		fmt.Println("File read failed", err)
		return
	}
	fmt.Printf("Number of bytes%d individual\n", n)
	fmt.Printf("The contents obtained are:%s\n", string(result[:]))
}

//The operation result is:
D:\goproject\src\dev_code\day25\demo3>go run main.go
 File opened successfully
 Number of bytes: 11
 The contents obtained are: hello world   

Example: what should I do when the read file content becomes a long document?

Using bufio to read, bufio encapsulates a layer of API based on file and supports more functions.

package main

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

//bufio read file
func main() {
	file, err := os.Open("./abc.txt")
	if err != nil {
		fmt.Println("File open failed", err)
		return
	}
	defer file.Close()
	//bufio buffer reads data
	reader := bufio.NewReader(file)
	for {
		str, err := reader.ReadString('\n')
		if err == io.EOF {
			fmt.Print(str)
			return
		}
		if err != nil {
			fmt.Println("File read failed", err)
			return
		}
		fmt.Print(str)
	}
}

//The operation result is:
D:\goproject\src\dev_code\day25\demo4>go run main.go
<Born in sorrow and die in happiness
 Shun hair in the mu, Fu Shuo in the plate building, glue in the fish and salt, Guan Yiwu in the scholar, sun shuao in the sea, Baili Xi in the city. Therefore, heaven will lower the great responsibility, so people must first work hard, work their muscles and bones, starve their body and skin, lack their body, and brush their actions. Therefore, they are moved and patient, which has benefited what they can't.
People can change after constant mistakes. They are trapped in the heart and balanced in consideration; Sign in color, send in sound, and then metaphor. If you enter, there will be no Legalists, and if you leave, there will be no enemy or foreign invasion. The country will die forever, and then you will know that you were born in hardship and died in happiness.
Author: Mencius

Example: ioutil convenient way to read files.

package main

import (
	"fmt"
	"io/ioutil"
)

//Read file contents in ioutil mode
func ReaderFile(path string) {
	content, err := ioutil.ReadFile(path)
	if err != nil {
		fmt.Println("File reading exception")
		return
	}
	fmt.Println(string(content))  //Convert string format and output
}

func main() {
	ReaderFile("./abc.txt")
}

//The operation result is:
D:\goproject\src\dev_code\day25\demo5>go run main.go
zhangsan
lisi
12345
abc123
abc456

Example: read parity line content.

package main

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

func main() {
	//read file
	file, err := os.Open("./abc.txt")
	if err != nil {
		fmt.Println("File open failed", err)
		return
	}
	//Execute file resource release before the end of main function
	defer file.Close()
	//bufio buffer read
	reader := bufio.NewReader(file)
	//Count parity rows
	count := 0
	for {
		str, _, err := reader.ReadLine()
		count++
		if err == io.EOF {
			// fmt.Println("file read complete")
			return
		}
		if err != nil {
			fmt.Println("File reading exception", err)
			return
		}
		if count%2 == 1 {
			fmt.Println(string(str))
		}
	}
}

//The operation result is:
D:\goproject\src\dev_code\day25\demo6>go run main.go
zhangsan
12345
abc456

Example: log in and judge whether the user name exists.

package main

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

//read file
func main() {
	//var doing bool
	var name string
	fmt.Print("enter one user name:")
	fmt.Scan(&name)
	//defer fmt.Println("user does not exist")
	file, err := os.Open("./abc.txt")
	if err != nil {
		fmt.Println("File open failed", err)
		return
	}
	//Before the main function ends, execute file resource release
	defer file.Close()

	//Using bufio buffer to read files
	reader := bufio.NewReader(file) //Create a buffer and put the contents of the file into the buffer
	//Count parity rows
	a := 0
	for {
		str, _, err := reader.ReadLine()
		//Each read, a+1
		a++
		if err == io.EOF {
			fmt.Println("File read complete")
			//If the file is not returned after reading, it indicates that the user does not exist
			fmt.Println("user does not exist")
			return
		}
		if err != nil {
			fmt.Println("File read error")
			return
		}
		if a%2 == 1 {
			if name == string(str) {
				fmt.Println("Login successful")
				return
			}
		}
	}
}

//The operation result is:
D:\goproject\src\dev_code\day25\demo7>go run main.go
 enter one user name:zhangsan
 Login successful

3. Write file

os. The openfile() function can open a file in the specified mode, so as to realize the functions related to file writing.

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

name:File name to open
flag:Open file mode

Mode type:

patternmeaning
os.O_WRONLYWrite only
os.O_CREATEcreate a file
os.O_RDONLYread-only
os.O_RDWRReading and writing
os.O_TRUNCempty
os.O_APPENDAdd

perm: file permission, an octal number. R (read) 04, w (write) 02, X (execute) 01.

Example: Write and WriteString.

package main

import (
	"fmt"
	"os"
)

//Write using write and writestring
func main() {
	//Open the file in write mode, create a new file, open write only mode, file permission 644
	file, err := os.OpenFile("abc.txt", os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		fmt.Println("File open failed", err)
		return
	}
	//Byte slice write
	file.Write([]byte("this is byte write\n"))
	//String write
	str := "this is string write"
	file.WriteString(str)
}

//The operation result is:
After executing the command, a message appears in the current directory abc.txt file
D:\goproject\src\dev_code\day25\demo8>go run main.go
 The contents are as follows:
this is byte write
this is string write

Example: bufio Write in newwriter mode.

package main

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

//bufio write
func main() {
	file, err := os.OpenFile("tmp.txt", os.O_CREATE|os.O_WRONLY, 0666)   //WRONLY, empty
	if err != nil {
		fmt.Println("File open failed", err)
		return
	}
	defer file.Close()

	//File write buffer
	write := bufio.NewWriter(file)
	for i := 0; i < 5; i++ {
		//Content write buffer
		write.WriteString("this is bufio write\n")
	}
	//Buffer data commit write file
	write.Flush()
}

//The operation result is:
After executing this command, a message appears tmp.txt file
D:\goproject\src\dev_code\day25\demo9>go run main.go
 The contents are as follows:
this is bufio write
this is bufio write
this is bufio write
this is bufio write
this is bufio write

Example: ioutil Write in WriteFile mode.

package main

import (
	"fmt"
	"io/ioutil"
)

func main() {
	str := "this is ioutil write\nthis is test content"
	//Write directly in iotuil mode, and convert the string into byte array
	err := ioutil.WriteFile("./tmp.txt", []byte(str), 0666)
	if err != nil {
		fmt.Println("File write failed", err)
		return
	}
}

//The operation result is:
When this command is executed, an error appears tmp.txt Documents
D:\goproject\src\dev_code\day25\demo10>go run main.go
 The contents are as follows:
this is ioutil write
this is test content

Tags: Go

Posted by lorne17 on Tue, 19 Apr 2022 02:15:01 +0930