文件读写

一、文件读取

1. 将整个文件读取到内存中

package main

import (
	"flag"
	"fmt"
	"io/ioutil"
)

func main() {
	//从命令行标记参数中获取文件路径
	fptr := flag.String("fpath", "test.txt", "the file path to read from")
	flag.Parse()
	data, err := ioutil.ReadFile(*fptr)
	if err != nil {
		fmt.Println("File reading error: ", err)
	}
	fmt.Println(string(data))
}

  

2. 分块读取文件

package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
)

func main() {
	fptr := flag.String("fpath", "test.txt", "the file path to read from")
	flag.Parse()

	f, err := os.Open(*fptr)
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		if err := f.Close(); err != nil {
			log.Fatal(err)
		}
	}()
	r := bufio.NewReader(f)
	b := make([]byte, 10)
	for {
		_, err := r.Read(b)
		if err != nil {
			if err == io.EOF {
				break
			}
			log.Fatal(err)
		}
		fmt.Println(string(b))
	}
}

  

3. 逐行读取文件

package main

import (
	"bufio"
	"flag"
	"fmt"
	"log"
	"os"
)

func main() {
	fptr := flag.String("fpath", "test.txt", "the file path to read from")
	flag.Parse()

	f, err := os.Open(*fptr)
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		if err = f.Close(); err != nil {
			log.Fatal(err)
		}
	}()
	s := bufio.NewScanner(f)
	for s.Scan() {
		fmt.Println(s.Text())
	}
	err = s.Err()
	if err != nil {
		log.Fatal(err)
	}
}

  

二、文件写入

1. 将字符串写入文件

package main

import (
	"fmt"
	"log"
	"os"
)

func main() {
	f, err := os.Create("test2.txt")
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		if err = f.Close(); err != nil {
			log.Fatal(err)
		}
	}()
	l, err := f.WriteString("Hello world")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(l, " bytes written successfully!")
}

  

2. 将字节写入文件

package main

import (
	"fmt"
	"log"
	"os"
)

func main() {
	f, err := os.Create("test2.txt")
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		if err = f.Close(); err != nil {
			log.Fatal(err)
		}
	}()
	d := []byte{104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100}
	l, err := f.Write(d)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(l, " bytes written successfully!")
}

  

3. 追加到文件

package main

import (
	"fmt"
	"log"
	"os"
)

func main() {
	f, err := os.OpenFile("test3.txt", os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		if err = f.Close(); err != nil {
			log.Fatal(err)
		}
	}()
	_, err = fmt.Fprintln(f, "Hello, my name is jet.")
	if err != nil {
		log.Fatal(err)
	}
}

  

 

转载于:https://www.cnblogs.com/wujuntian/p/11612987.html

你可能感兴趣的:(文件读写)