前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Golang之文件读写

Golang之文件读写

作者头像
超蛋lhy
发布2018-08-31 15:34:23
1.2K0
发布2018-08-31 15:34:23
举报
文章被收录于专栏:Pythonista

读写文件,不添加文件路径,默认写入到GOPATH路径下

终端读写:

源码

代码语言:javascript
复制
func Sscanf
func Sscanf(str string, format string, a ...interface{}) (n int, err error)
代码语言:javascript
复制
解释: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.
代码语言:javascript
复制
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缓冲:

源码

代码语言:javascript
复制
func NewReader
func NewReader(rd io.Reader) *Reader
NewReader returns a new Reader whose buffer has the default size.

-

代码语言:javascript
复制
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)
}

打开文件,读取

代码语言:javascript
复制
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源码

代码语言:javascript
复制
    /*
    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.
     */

 -读取一行的字符个数

代码语言:javascript
复制
package main

import (
    "fmt"
    "os"
)

/*
从终端读取一行字符串,统计英文、数字、空格以及其他字符的数量
*/
import (
    "bufio"
    "io"
)

type CharCount struct {
    ChCount    int
    NumCount   int
    SpaceCount int
    OtherCount int
}

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()
    var count CharCount
    reader := bufio.NewReader(file)

    for {
        str, err := reader.ReadString('\n')
        if err == io.EOF {
            break
        }
        if err != nil {
            fmt.Printf("read file failed,err:%v", err)
            break
        }
        runeArr := []rune(str)
        for _, v := range runeArr {
            switch {
            case v >= 'a' && v <= 'z':
                fallthrough
            case v >= 'A' && v <= 'Z':
                count.ChCount++
            case v == ' ' || v == '\t':
                count.SpaceCount++
            case v >= '0' && v <= '9':
                count.NumCount++
            default:
                count.OtherCount++
            }
        }
    }
    fmt.Printf("char count:%d\n", count.ChCount)
    fmt.Printf("num count:%d\n", count.NumCount)
    fmt.Printf("space count:%d\n", count.SpaceCount)
    fmt.Printf("other count:%d\n", count.OtherCount)
}

 文件写入

--

代码语言:javascript
复制
package main

import (
    "bufio"
    "fmt"
    "os"
)
func main(){
    outputFile,outputError:=os.OpenFile("output.dat",os.O_WRONLY|os.O_CREATE,0666)
    if outputError!=nil{
        fmt.Printf("An error occurred with file crea ion\n")
        return
    }
    //在函数执行结束前,一定要关闭,谨记
    defer outputFile.Close()
    outputWriter:=bufio.NewWriter(outputFile)
    outputString:="hello world!\n"
    for i:=0;i<10;i++{
        outputWriter.WriteString(outputString)
    }
    outputWriter.Flush()//刷新落地
}

golang的复制文件

代码语言:javascript
复制
package main

import (
    "fmt"
    "io"
    "os"
)

func main() {
    //os.Args是string的切片,用来存储所有的命令行参数
    w, err := CopyFile(os.Args[1], os.Args[2])
    if err != nil {
        fmt.Println(err.Error())
    }
    fmt.Println(w)
}
func CopyFile(dstName, srcName string) (written int64, err error) {
    src, err := os.Open(srcName)
    if err != nil {
        return
    }
    defer src.Close()
    dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
    if err != nil {
        return
    }
    defer dst.Close()
    //把src内容写进dst里面
    return io.Copy(dst, src)
}

命令行参数

代码语言:javascript
复制
package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Printf("len of args:%d\n", len(os.Args))
    for i, v := range os.Args {
        fmt.Printf("args[%d]=%s\n", i, v)
    }
}

flag包用于实现命令行参数

例如Linux下的 ls -l

代码语言:javascript
复制
package main

import (
    "flag"
    "fmt"
)
//flag包支持命令行参数
func main() {
    var confPath string
    var logLevel int
    flag.StringVar(&confPath, "c", "", "Please input conf path")
    flag.IntVar(&logLevel, "d", 0, "PLEASE INPUT LOG LEVEL")
    flag.Parse()
    fmt.Println("path:", confPath)
    fmt.Println("log leve:", logLevel)
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-01-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 终端读写:
  • 文本I/O缓冲:
  • 打开文件,读取
  •  -读取一行的字符个数
  •  文件写入
  • golang的复制文件
  • 命令行参数
  • flag包用于实现命令行参数
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档