golang读写数据

1. 从键盘和标准输入os.Stdin读取输入,最简单的方法是使用fmt包提供的Scan和Sscan开头的函数。

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 扫描来自标准输入的文本,将空格分隔的值依次存放到后续的参数内,直到碰到换行。

Scanf的第一个参数是格式串,其他都相同。

Sscan及开头的函数输入变成了string,Fscan及开头的函数输入变成了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相关:

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)

通过Fprintln()写文件

    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.读文件

os包读取文件

文件使用执行os.File类型的指针来表示,也叫作文件句柄。标准输入输出os.Stdin/os.Stdout都是*os.File。

os包包含操作文件的底层处理函数,类似unix系统调用。

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()默认的mode为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包读取文件

ioutil将整个文件的内容读到一个内存中。

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

示例:

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包缓冲读取(buffered reader)文件

        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)
        }

相关函数:

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)从输入中读取内容,直到碰到 delim 指定的字符,然后将读取到的内容连同 delim 字符一起放到缓冲区。ReadBytes()类似,但ReadByte()仅读取一个字节。

ReadString()只能读取字符串,Read()可以读取任何数据,包括二进制文件。

    r := bufio.NewReader(f)
    b := make([]byte, 3)
    for {
        _, err := r.Read(b)  //每次读取3个字节
        if err != nil {
            fmt.Println("Error reading file:", err)
            break
        }
        fmt.Println(string(b))
    }

bufio逐行读取文件

    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)
    }

相关函数:

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.命令行参数读取

os包中有一个string类型的切片变量os.Args,其用来处理一些基本的命令行参数,它在程序启动后读取命令行输入的参数。参数会放置在切片os.Args[]中(以空格分隔),从索引1开始(os.Args[0]放的是程序本身的名字)。

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

flag包可以用来解析命令行选项,但通常被用来替换基本常量。例如,在某些情况下希望在命令行给常量一些不一样的值。

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
}

flag的使用规则是:首先定义flag(定义的flag会被解析),然后使用Parse()解析flag,解析后已定义的flag可以直接使用,未定义的剩余的flag可通过Arg(i)单独获取或通过Args()切片整个获取。

定义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)

解析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

参考:

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

猜你喜欢

转载自www.cnblogs.com/embedded-linux/p/11128903.html
今日推荐