read and write data golang

1. The read input from the keyboard, and standard input os.Stdin, the easiest way is to use a function provided by the package fmt and Sscan Scan beginning.

func Scan(a ...interface{}) (n int, err error)
func Scanf(format string, a ...interface{}) (n int, err error)
func Scanln(a ...interface{}) (n int, err error)
func Sscan(str string, a ...interface{}) (n int, err error)
func Sscanf(str string, format string, a ...interface{}) (n int, err error)
func Sscanln(str string, a ...interface{}) (n int, err error)
func Fscan(r io.Reader, a ...interface{}) (n int, err error)
func Fscanf(r io.Reader, format string, a ...interface{}) (n int, err error)
func Fscanln(r io.Reader, a ...interface{}) (n int, err error)

Scanln scanned text from standard input, the space-separated values ​​sequentially stored into the subsequent parameters until it has wrap.

The first parameter is the format string Scanf, others are the same.

Sscan and the beginning of the function of the input into a string, Fscan and the beginning of the function of the input into a io.Reader.

Scan, Fscan, Sscan treat newlines in the input as spaces.

Scanln, Fscanln and Sscanln stop scanning at a newline and require that the items be followed by a newline or EOF.

        fmt.Println("Please enter your full name: ")
        fmt.Scanln(&firstName, &lastName)
        fmt.Printf("Hi %s %s!\n", firstName, lastName)
        fmt.Sscanf("30.0 * 25 * hello", "%f * %d * %s", &f, &i, &s)
        fmt.Println("From the string we read: ", f, i, s)
        fmt.Println("Please enter string: ")
        fmt.Scan(&s)
        fmt.Println(s)

printf Related:

func Fprint(w io.Writer, a ...interface{}) (n int, err error)
func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)
func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)
func Fprintln(w io.Writer, a ...interface{}) (n int, err error)

By Fprintln () to write files

    const name, age = "Kim", 22
    n, err := fmt.Fprintln(os.Stdout, name, "is", age, "years old.")

    // The n and err return values from Fprintln are
    // those returned by the underlying io.Writer.
    if err != nil {
        fmt.Fprintf(os.Stderr, "Fprintln: %v\n", err)
    }
或
    for _, v := range d {
        fmt.Fprintln(f, v)
        if err != nil {
            fmt.Println(err)
            return
        }
    }

2. Reading file

os package to read the file

File type performed using os.File pointer to indicate, also known as file handles. Standard input and output os.Stdin / os.Stdout are * os.File.

Os package contains the underlying processing function of the file operation, similar to the unix system call.

type File struct {
        // contains filtered or unexported fields
}
func Open(name string) (*File, error)
func OpenFile(name string, flag int, perm FileMode) (*File, error)
func (f *File) Read(b []byte) (n int, err error)
func (f *File) Write(b []byte) (n int, err error)
func (f *File) WriteString(s string) (n int, err error)

Open () the default mode is O_RDONLY.

        inputFile, inputError := os.Open("test.txt")
        if inputError != nil {
                fmt.Printf("An error occurred on openning th inputfile\n")
                return
        }

        defer inputFile.Close()
        inputReader := bufio.NewReader(inputFile)
        for {
                inputString, readerError := inputReader.ReadString('\n')
                if readerError == io.EOF {
                        return
                }
                fmt.Printf("The input was: %s", inputString)
        }

io / ioutil packet read files

ioutil read the entire contents of a file in memory.

func ReadFile(filename string) ([]byte, error)
func WriteFile(filename string, data []byte, perm os.FileMode) error

Example:

package main
import (
        "fmt"
        "io/ioutil"
)

func main(){
//      data, err := ioutil.ReadFile("/home/golang/file/test.txt")
        data, err := ioutil.ReadFile("./test.txt")
        if err != nil {
                fmt.Println("File reading error", err)
                return
        }
        fmt.Println("Contents of File:", string(data))
}

bufio packet buffer read (buffered reader) file

        var inputReader *bufio.Reader
        var input string
        var err error

        inputReader = bufio.NewReader(os.Stdin)
        fmt.Println("Please Enter some input:")
        input, err = inputReader.ReadString('\n')
        if err == nil {
                fmt.Printf("The input was: %s\n", input)
        }

related functions:

func NewReader(rd io.Reader) *Reader
func (b *Reader) ReadString(delim byte) (string, error)
func (b *Reader) ReadByte() (byte, error)
func (b *Reader) ReadBytes(delim byte) ([]byte, error)
func (b *Reader) Read(p []byte) (n int, err error)

ReadString (delim byte) read from the input until the specified character delim encountered, then the contents of the read character delim put together with the buffer. ReadBytes () is similar, but ReadByte () reads only one byte.

The ReadString () can only read a string, the Read () to read any data, including binary files.

    R & lt: = bufio.NewReader (F) 
    B: = the make ([] byte , . 3 )
     for {
         _, ERR: = r.Read (B) // read three bytes each 
        IF ERR =! nil { 
            FMT .Println ( " Error Reading File: " , ERR)
             BREAK 
        } 
        fmt.Println ( String (B)) 
    }

bufio read the file line by line

    f, err := os.Open("./test.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
        log.Fatal(err)
    }
    }()
    s := bufio.NewScanner(f)
    for s.Scan() {
        fmt.Println(s.Text())
    }
    err = s.Err()
    if err != nil {
        log.Fatal(err)
    }

related functions:

func NewScanner(r io.Reader) *Scanner
func (s *Scanner) Scan() bool
func (s *Scanner) Text() string

NewScanner returns a new Scanner to read from r. The split function defaults to ScanLines.

4. Command-line arguments to read

os package includes a slice of type string variable os.Args, which is used to process some of the basic command-line arguments, it reads the parameters in the command line after the program starts. Parameter will be placed in the slice os.Args [] in the (separated by spaces), start from the index 1 (os.Args [0] to put the name of the program itself).

fmt.Println("Parameters:", os.Args[1:])

flag packet parse command line option can be used, but usually is used to replace substantially constant. For example, in some cases, the command line to the constant hope some different values.

type Flag struct {
    Name     string // name as it appears on command line
    Usage    string // help message
    Value    Value  // value as set
    DefValue string // default value (as text); for usage message
}

The use of flag rules are: First define flag (flag definitions are parsed), then use the Parse () parse flag, flag parsed defined may be used as the flag may be defined by a surplus Arg (i) obtained separately or () get through the entire slice Args.

Definition of flag

func String(name string, value string, usage string) *string
func StringVar(p *string, name string, value string, usage string)
func Int(name string, value int, usage string) *int
func IntVar(p *int, name string, value int, usage string)

Parsing flag

func Parse()

Parse() parses the command-line flags from os.Args[1:]. Must be called after all flags are defined and before flags are accessed by the program.

func Arg(i int) string
func Args() []string

Arg returns the i'th command-line argument. Arg(0) is the first remaining argument after flags have been processed.

Args returns the non-flag command-line arguments.

After parsing, the arguments following the flags are available as the slice flag.Args() or individually as flag.Arg(i). The arguments are indexed from 0 through flag.NArg()-1.

func NArg() int

NArg is the number of arguments remaining after flags have been processed.

Flags may then be used directly. If you're using the flags themselves, they are all pointers; if you bind to variables, they're values.

package main
import (
        "fmt"
        "flag"
)

func main(){
        var new_line = flag.Bool("n", false, "new line")
        var max_num int
        flag.IntVar(&max_num, "MAX_NUM", 100, "the num max")

        flag.PrintDefaults()
        flag.Parse()

        fmt.Println("There are", flag.NFlag (),"remaining args, they are:", flag.Args())
        fmt.Println("n has value: ", *new_line)
        fmt.Println("MAX_NJUM has value: ", max_num)
}
$ go build -o flag flag.go
$ ./flag
  -MAX_NUM int
        the num max (default 100)
  -n    new line
There are 0 remaining args, they are: []
n has value:  false
MAX_NJUM has value:  100
$ ./flag -n -MAX_NUM=1000 wang qin
  -MAX_NUM int
        the num max (default 100)
  -n    new line
There are 2 remaining args, they are: [wang qin]
n has value:  true
MAX_NJUM has value:  1000

 

reference:

1.   https://golang.google.cn/pkg/fmt/#Scanln

2.   https://www.kancloud.cn/kancloud/the-way-to-go/72678

3.   https://studygolang.com/subject/2

Guess you like

Origin www.cnblogs.com/embedded-linux/p/11128903.html