Golang 文件操作


读取文件

1. 基本用法

func readFile(filename string) string {
	f, err := os.Open(filename)
	if err != nil {
		fmt.Println("Cannot open file: %s\n", filename)
	}
	defer f.Close()

	buf := make([]byte, 1024)

	for {
		n, err := f.Read(buf)
		if err != nil && err != io.EOF {
			panic(err)
		}
	}
}

2. bufio 操作

func readFile(filename string) {
	f, err := os.Open(filename)
	if err != nil {
		fmt.Println("Cannot open file: %s\n", filename)
	}
	defer f.Close()

	r := bufio.NewReader(f)

	buf := make([]byte, 1024)

	for {
		n, err := r.Read(buf)
		if err != nil && err != io.EOF {
			panic(err)
		}
	}
}

3. ioutil 操作

func readFile(filename string) {
	f, err := os.Open(filename)
	if err != nil {
		fmt.Println("Cannot open file: %s\n", filename)
	}
	defer f.Close()

	fd, err := ioutil.ReadAll(f)

	return string(fd)
}

4. Scanner 用法

单纯考虑逐行读取,bufio 的文档是推荐使用Scanner

func readFile(filename string) {
    f, err := os.Open(filename)
    if err != nil {
        fmt.Println("Cannot open file: %s\n", filename)
    }
    defer f.Close()

    scanner := bufio.NewScanner(f)

    for scanner.Scan() {
        // 行
        fmt.Println(scanner.Text())
    }

}