Writing in the front
In our last article, “Reading and writing data in Golang (Part 1)”, we introduced some simple reading and writing operations in Golang. Next, we will continue to learn about reading and writing data in Golang.
Read parameters from the command line
In some scenarios, we are executing a piece of software, and sometimes we need to pass in some initialization information, such as attributes like USERNAME and password to connect to the database. So how do you read parameters in Golang? Look at the following example:
useos.Args
To obtain parameters
package main
import (
"fmt"
"os"
)
func main(a) {
if len(os.Args) > 1 {
for i:=1; i<len(os.Args); i++ { sayHello(os.Args[i]) } }else {
fmt.Println("Parameter null")}}func sayHello(name... string) {
fmt.Println("hello!",name)
}
Copy the code
Output:
Note:
This command line argument is placed in the sliced os.args [] (separated by Spaces), starting at index 1 (os.args [0] puts the name of the program itself). The strings.Join function joins these parameters with Spaces apart.
useflag.Args
To obtain parameters
package main
import (
"flag"
"fmt"
)
func main(a) {
flag.Parse()
for _, arg := range flag.Args() {
sayHello(arg)
}
}
func sayHello(name... string) {
fmt.Println("hello!",name)
}
Copy the code
Output:
Note:
Flag.arg (0) is the first real flag, not the name of the placement program like os.args (0).
One example: use cache to read files withflag.Args
Comprehensive application of
For those of you who are familiar with Linux, the cat filename command will be used. Next, we will use Golang to implement this gadget.
Requirements describe
We need a gadget to print the contents of a file and give the user a friendly reminder when the file doesn’t exist.
Functional design
- The file is read into the cache and printed in batches based on the filename entered by the user
- Print “No file {filename}” when file does not exist
Code:
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
)
func main(a) {
flag.Parse()
filename :=flag.Arg(0)
if filename=="" {
fmt.Println("Command Usage Format: mycat filename")
return
}
open, err := os.Open(filename)
defer open.Close()
iferr! =nil {
fmt.Println(err)
return
}
myCat(bufio.NewReader(open))
}
func myCat(reader *bufio.Reader) {
for {
buf, err := reader.ReadBytes('\n')
fmt.Fprintf(os.Stdout, "%s\n", buf)
if err == io.EOF {
break}}return
}
Copy the code
Testing:
- Print the contents of the file when the file exists:
- Give a hint when the file does not exist:
Here’s a question: Does this program meet the requirements?
You can think about what happens if the printed file is a large file with only one line of data.
Therefore, to avoid this situation, we will modify MyCat.
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
)
func main(a) {
flag.Parse()
filename :=flag.Arg(0)
if filename=="" {
fmt.Println("Command Usage Format: mycat filename")
return
}
file, err := os.Open(filename)
defer file.Close()
iferr! =nil {
fmt.Println(err)
return
}
myCatV2(bufio.NewReader(file))
}
func myCatV2(reader *bufio.Reader) {
buf := make([]byte.512)
for {
n, err := reader.Read(buf)
fmt.Fprintf(os.Stdout,"%s",buf[0:n])
if err ==io.EOF {
break}}return
}
Copy the code
In this version, we specify the size of the cache, which is a 512-bit byte array.
Output:
We specify the buffer size to avoid loading the entire file into memory.
Of course, you can continue to make improvements to the program, such as introducing coroutines, which are beyond the scope of this article.
One important point: usedefer
Close the file
In the previous article, we introduced the role of the defer keyword: it executes the statement it decorates when the function exits (after the return). Here, we use it to close the file before the main function exits.
Write in the last
So much for reading command line arguments and combining them with file reads and writes in Golang. The examples covered 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 data formatting and data network transfer in Golang.