golang 读写文件内容(备份)

前端之家收集整理的这篇文章主要介绍了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.f2er.com/go/191386.html

猜你在找的Go相关文章