微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

golang 读写文件内容(备份)

以下是读取文件内容
package main
import (
    "bufio"
    "fmt"
    "io"
    "os"
    "strings"
)
func main() {
    fh,ferr := os.Open("d:\\n.txt")
    if ferr != nil {
        fmt.Printf("An error occurred on opening the inputfile\n" +
            "Does the file exist?\n" +
            "Have you got acces to it?\n")
        return 
    }
    defer fh.Close()
    inputread := bufio.NewReader(fh)
    for {
        input,ferr := inputread.ReadString('\n')
        if ferr == io.EOF {
            return
        }
        fmt.Println(strings.Trimspace(input))
    }
}


读取gzip格式文件

package main

import (
	"bufio"
	"compress/gzip"
	"fmt"
	"os"
)

func main() {
	fName := "MyFile.gz"
	var r *bufio.Reader
	fi,err := os.Open(fName)
	if err != nil {
		fmt.Fprintf(os.Stderr,"%v,Can't open %s: error: %s\n",os.Args[0],fName,err)
		os.Exit(1)
	}
	fz,err := gzip.NewReader(fi)
	if err != nil {
		r = bufio.NewReader(fi)//解压失败(还是读取原来文件)gz文件还是读取原始文件
	} else {
		r = bufio.NewReader(fz)//解压成功后读取解压后的文件
	}
	for {
		line,err := r.ReadString('\n')
		if err != nil {
			fmt.Println("Done reading file")
			os.Exit(0)
		}
		fmt.Println(line)
	}
}


文件:
package main

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

func main() {
	outputFile,outputError := os.OpenFile("output.dat",os.O_WRONLY|os.O_CREATE,0666)//0666是标准的权限掩码,关于打开标识看下面
	if outputError != nil {
		fmt.Printf("An error occurred with file creation\n")
		return
	}
	defer outputFile.Close()
	outputWriter := bufio.NewWriter(outputFile)
	outputString := "Hello World!\n"
	for i := 0; i < 10; i++ {
		outputWriter.WriteString(outputString)
	}
	outputWriter.Flush()
}
os.O_RDONLY : the read flag for read-only access os.WRONLY : the write flag for write-only access os.O_CREATE : the create flag: create the file if it doesn’t exist os.O_Trunc : the truncate flag: truncate to size 0 if the file already exists

原文地址:https://www.jb51.cc/go/191386.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐