码迷,mamicode.com
首页 > 其他好文 > 详细

Golang之文件读写

时间:2018-01-17 13:50:53      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:iter   lin   文件读写   determine   string   err   amp   return   scanner   

终端读写:

源码

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

标签:iter   lin   文件读写   determine   string   err   amp   return   scanner   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!