Writing in the front
In the previous article, we learned how to build the Golang development environment, learn the common data structures in Golang, learn the basic flow control statements, learn the functions and structures and other content, and then we will start to learn the file reading and writing in Golang.
Read user input on the console
In Golang, how do you read user input on the console? In this case, we can use the Scan function in the FMT package.
Look at the following example:
package main
import "fmt"
func main(a) {
var firstname,lastname string
fmt.Println("Please enter your name:")
_, _ = fmt.Scanln(&firstname, &lastname)
fmt.Printf("Hello! % s. % s \ n", lastname, firstname)
}
Copy the code
Output:
Please enter your name: Hello Han Li! Make hanCopy the code
Scanln scans text from standard input, storing space-separated values in subsequent arguments until a newline is hit. Scanf is similar, except that the first argument to Scanf is used as a format string to determine how to read. Sscan and functions that begin with Sscan are read from strings, otherwise the same as Scanf. If these functions read different results than you expected, you can check the number of successful readings and the errors returned.
In addition, we can use the Buffered Reader provided by the Bufio package to read data
Look at the following example:
package main
import (
"bufio"
"fmt"
"os"
)
func main(a) {
fmt.Println("Please enter a paragraph.")
inputReader := bufio.NewReader(os.Stdin)
s,err := inputReader.ReadString('\n')
if err == nil {
fmt.Println("You typed:")
fmt.Println(s)
}
}
Copy the code
Output:
Please input a paragraph of text last year today in this door people face peach blossom set off red. People do not know where the peach blossom is still smiling spring breeze. You input is: last year today this door in the face of peach blossom set off red. People do not know where the peach blossom is still smiling spring breeze.Copy the code
File to read and write
File read operation
In Go, files are represented by a pointer to type os.File, also known as a File handle.
According to the line read
Look at the following example:
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func main(a) {
inputFile, err := os.Open("G:\\06_golangProject\\golang\\doc\\ Base part \\ 10_golang.md")
defer inputFile.Close()
iferr! =nil {
fmt.Println(err)
}
input :=bufio.NewReader(inputFile)
for{
readString, err := input.ReadString('\n')
fmt.Println(readString)
if err==io.EOF {
fmt.Println(err)
return}}}Copy the code
In this example, we Open a file using os.open and print the file line by line in a loop until it is printed.
Buffered file read
Unfortunately, in many cases, the contents of a file are not divided into lines, and sometimes the file is even a binary file. How do we read it?
Take a look at this example:
package main
import (
"fmt"
"io"
"os"
)
func main(a) {
buf := make([]byte.1024)
inputFile, err := os.Open("G:\\06_golangProject\\golang\\doc\\ Base part \\ 10_golang.md")
defer inputFile.Close()
iferr! =nil {
fmt.Println(err)
}
for {
_, err := inputFile.Read(buf)
if err==io.EOF {
return
}
fmt.Println(string(buf))
}
}
Copy the code
We define a []byte cache that stores and prints what we read when we read a file. This way, we don’t have to worry about how the contents of the file are divided.
File write operation
The Golang file read operation is a simple introduction to the file write operation, see the following example:
package main
import (
"bufio"
"fmt"
"os"
)
func main(a) {
file, err := os.OpenFile("Gudandan fang.txt", os.O_WRONLY|os.O_CREATE, 0666)
iferr ! =nil {
fmt.Println("Error opening file")
return
}
defer file.Close()
// Create a buffer
writer := bufio.NewWriter(file)
s := "Hello World\n"
for i := 0; i < 10; i++ {
// Write to the buffer
_, _ = writer.WriteString(s)
}
// Write buffer data to file
_ = writer.Flush()
}
Copy the code
OpenFile(name string, flag int, perm FileMode) (*File, error). As you can see, it takes three parameters, the first parameter is the file name, the second parameter is the open flag (we open the file with write only and create it if it doesn’t exist), and the third parameter is the file permission.
For the second parameter, when there are multiple sign use logical operators | connection, common signs include the following:
os.O_RDONLY
: read onlyos.O_WRONLY
: just writeos.O_CREATE
: Create: Creates the specified file if it does not exist.os.O_TRUNC
: Truncate: If the specified file already exists, the length of the file is truncated to 0.
File permissions are ignored when the file is read, so the third argument passed in when using OpenFile can be 0. When writing files, whether Unix or Windows, use 0666.
File copy
I don’t know if you still remember, Han Li used two herbal medicines in the cave during the period of building a foundation for his Uncle Lei’s Dan fang. Of course, he did not give him the ancient formula directly, but gave han Li a copy of the Dan fang to the jade Jane.
So? How to copy source. TXT to target.txt in Golang? Take a look at this example:
package main
import (
"fmt"
"io"
"os"
)
func main(a) {
copyFile("Gudandan fang.txt"."Jade Jane for Han Li. TXT")
fmt.Println("Copy done!")}func copyFile(source, target string) {
openFile, err := os.Open(source)
iferr! =nil {
fmt.Println("Error opening source file")
return
}
defer openFile.Close()
createFile, err := os.Create(target)
iferr! =nil {
fmt.Println("Error creating target file")
return
}
defer createFile.Close()
written, err := io.Copy(createFile, openFile)
iferr ! =nil {
fmt.Println(err)
}
fmt.Println(written)
}
Copy the code
Copy is the first argument to the target file name and the second argument to the source file.
Write in the last
That’s the first half of Golang’s article on file reading and writing. The examples in this article can be downloaded here. If my study notes can help you, please give me a thumbs up and encouragement. If there are mistakes and omissions in the article, please help to correct them.
In the next article, we’ll take a look at Golang reading command line arguments and data network transfers in Golang.