Golang之文件读写

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Golang之文件读写相关的知识,希望对你有一定的参考价值。

终端读写:

源码

func Sscanf
func Sscanf(str string, format string, a ...interface{}) (n int, err error)
解释:Sscanf scans the argument string, storing successive space-separated values into successive arguments as determined by the format.
It returns the number of items successfully parsed. Newlines in the input must match newlines in the format.
package main

import "fmt"

//终端读写
type student struct {
    Name  string
    Age   int
    Score float32
}

func main() {
    var str = "stu01 18 89.92"
    var stu student
    fmt.Sscanf(str, "%s %d %f", &stu.Name, &stu.Age, &stu.Score)
    fmt.Println(stu)
}

文本I/O缓冲:

源码

func NewReader
func NewReader(rd io.Reader) *Reader
NewReader returns a new Reader whose buffer has the default size.

-

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    str, err := reader.ReadString(\n)
    if err != nil {
        fmt.Println("read string,err:", err)
        return
    }
    fmt.Printf("read str succ,ret:%s\n", str)
}

打开文件,读取

package main

import (
    "bufio"
    "fmt"
    "os"
)

//读取文件

func main() {
    //打开一个文件
    file, err := os.Open("D:/project/src/go_dev/day7/example4/123.log")
    if err != nil {
        fmt.Println("read file err:", err)
        return
    }
    //重点,文件要关闭
    defer file.Close()
    /*
        func NewReaderSize
        func NewReaderSize(rd io.Reader, size int) *Reader
            NewReaderSize returns a new Reader whose buffer has at least the specified size.
            If the argument io.Reader is already a Reader with large enough size, it returns the underlying Reader.
    */
    reader := bufio.NewReader(file)
  //文件若不是换行结尾,就算出错 str, err :
= reader.ReadString(\n) if err != nil { fmt.Println("read string failed,err:", err) return } fmt.Printf("read str success,result:%s\n", str) }

ReadString源码

    /*
    func (*Reader) ReadString ¶

func (b *Reader) ReadString(delim byte) (string, error)
ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter.
    If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF).
    ReadString returns err != nil if and only if the returned data does not end in delim. For simple uses, a Scanner may be more convenient.
     */

 

以上是关于Golang之文件读写的主要内容,如果未能解决你的问题,请参考以下文章

golang代码片段(摘抄)

Golang进阶实战之IO操作

代码片段 - Golang 实现简单的 Web 服务器

代码片段 - Golang 实现集合操作

Golang读写文件的几种方式

GoLang读写数据---中