Use of go language basic seek cursor position OS package

Time:2021-7-30

Syntax:

os.Open()–>*File,err *****

File. Seek (offset, where) to set the unknown value of the cursor

Offset

Where, where to start: 0 from the beginning, 1 from the current, 2 from the end

package main
import (
   "os"
   "fmt"
)
func main()  {
   /*
   Seek (offset int, where int) indicates to set the position of the cursor
      Offset int, set the number of bytes
   Where int, where to start
      0, from the beginning of the file
      1. Current position
      2. Distance from the end of the file
    */
    //file,_:= os.Open("C:\\liu\\pro\\aa.txt") //RDONLY
    file,_:=os.OpenFile("C:\\liu\\pro\\aa.txt",os.O_RDWR,0)
    //1. After opening the file, the cursor is at the beginning of the file by default.
    bs := make([] byte, 1)
    defer file.Close()
    //2.seek()
    //Set the cursor position: 4 bytes from the beginning of the file.
    //file.Seek(8,0)
    count, _:= file.Read(bs)
   fmt.Println(string(bs[:count])) //a
    file.Seek(4,2)
   //count, _= file.Read(bs)
   //fmt.Println(string(bs[:count])) //
   file.Write([]byte{65,66,67})
   FMT. Println ("finished.")
}

Supplement: go language – command line parameters (os.args, flag package)

Most go programs have no UI. They run in pure command-line mode. What to do depends on the running parameters.

Here are the go language command line programs and their parameters.

1. os.Args

The program obtains the parameters given by the runtime, which can be realized through the OS package. Look at the code first:

package main
import (
 "fmt"
 "os"
 "strconv"
)
func main () {
 for idx, args := range os.Args {
  FMT. Println ("parameter" + strconv.itoa (IDX) + ":", args)
 }
}

The results are as follows:

$go run main.go 1 3 -X ?

Parameter 0: / TMP / go build116558042 / command line arguments/_ obj/exe/main

Parameter 1: 1

Parameter 2: 3

Parameter 3: – x

Parameter 4:?

You can see that the command line parameters include the program path itself and parameters in the general sense.

The type of os.args in the program is [] string, that is, string slice. Therefore, it can be traversed in the range of the for loop, and the number can be obtained by Len (OS. Args).

If you do not want to output the first value of os.args, that is, the information of the executable file itself, you can modify the above program:


for idx, args := range os.Args[1:] {

Slice the slice after range and remove the first element.

There is a more concise way to output all the elements of the slice:

fmt.Println(strings.Join(os.Args[1:], "\n"))
fmt.Println(os.Args[1:])
/*
The result of the latter method is [1 3 - x?], This is the format of fmt.println output slice
*/

2. Flag package

The flag package provides a stronger capability than simply analyzing command line parameters through os.args slices.

Let’s take an example:

package main
import (
	"fmt"
	"flag"
)
Var B = flag.bool ("B", false, "bool type parameter")
Var s = flag.string ("s", "string type parameter")
func main() {
	flag.Parse()
	fmt.Println("-b:", *b)
	fmt.Println("-s:", *s)
	FMT. Println ("other parameters:", flag. Args())
}
------------------------------------
$ go run main.go
-b: false
-s: 
Other parameters: []
------------------------------------
$ go run main.go -b
-b: true
-s: 
Other parameters: []
------------------------------------
$ go run main.go -b -s test others
-b: true
-s: test
Other parameters: [Others]
------------------------------------
$ go run main.go  -help
Usage of /tmp/go-build080353851/command-line-arguments/_obj/exe/main:
  -b 	 Bool type parameter
  -s string
    	String type parameter
exit status 2

2.1 defining parameters

Using the flag package, first define the command line parameters to be parsed, that is, the parameters starting with “-“, such as – B – S – help here- Help does not need to be specified and can be processed automatically.

Two parameters are specified here, – B and – s:

Var B = flag.bool ("B", false, "bool type parameter")
Var s = flag.string ("s", "string type parameter")
-----------------
Prototype:
func Bool(name string, value bool, usage string) *bool
func String(name string, value string, usage string) *string

Through flag.bool and flag.string, two pointers B and s are established to point to variables of bool type and string type respectively. Therefore, variable values will be used later through * B and * s.

There are three parameters of flag.bool and flag.string, which are the command line parameter name, default value and prompt string.

parameter function
name Command line parameter names, such as – B, – help
value Default value. For parameters not explicitly specified, an implicit default value is given. For example, * b = false if – B is not given in this example
usage Prompt message: if the parameters given are incorrect or you need to view help, the string specified here will be given

2.2 analytical parameters

Before using flag, you must first parse:


flag.Parse()

2.3 service parameters

As explained above, the parameter variable pointer defined by the flag method can be used through indirect reference:


fmt.Println("-b:", *b)
fmt.Println("-s:", *s)

2.4 unresolved parameters

There is no part of the parameter that can be parsed according to the predefined parameters. It can be obtained through flag. Args(). It is a string slice.

FMT. Println ("other parameters:", flag. Args())

It should be noted that starting from the first parameter that cannot be resolved, all subsequent parameters cannot be resolved. Even if the following parameters contain predefined parameters:

$ go run main.go -b stop -s test others
-b: true
-s: 
Other parameters: [stop - s test others]

In the above example, when it is parsed to stop, it cannot continue parsing. Even if the predefined – s is given later, it cannot be obtained.

The above is my personal experience. I hope I can give you a reference, and I hope you can support developpaer. If you have any mistakes or don’t consider completely, please don’t hesitate to comment.

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]