首页 > 其他 > 详细

Golang之文件读写

时间:2018-01-17 13:21:19      阅读:215      评论:0      收藏:0      [点我收藏+]

终端读写:

源码

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之文件读写

原文:https://www.cnblogs.com/pyyu/p/8302196.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!