package main import "fmt" import "os" import "io" import "bufio" import "io/ioutil" func main() { myfile := "debug.txt" test_write_file(myfile) test_read_file(myfile) test_open_or_create_file() test_bufio() test_ioutil(); } /*写文件内容*/ func test_write_file(filename string) { fp, err := os.Create(filename) if (err != nil) { fmt.Println(err) return } for i := 0; i < 10; i++ { ourstr := fmt.Sprintf("%s:%d\n", "Hello World", i) fp.WriteString(ourstr) fp.Write([]byte("abcd\n")) } fp.Close() } /*读取文件内容*/ func test_read_file(filename string) { fp, err := os.Open(filename) if err != nil { fmt.Println(err) } defer fp.Close() buf := make([]byte, 1024) for { n, _ := fp.Read(buf) if n == 0 { break } os.Stdout.Write(buf) } } /*同时使用os.Open与os.Create操作文件*/ func test_open_or_create_file() { openFile := "log.txt" fo, err := os.Open(openFile) if err != nil { fmt.Println(err) } defer fo.Close() createFile := "log_new.txt" fc, err := os.Create(createFile) if err != nil { fmt.Println(err) } defer fc.Close() buf := make([]byte, 1024) for { rn, err := fo.Read(buf) if err != nil && err != io.EOF { fmt.Println(err) panic(err) } fmt.Println(rn) if rn == 0 { break } wn, err := fc.Write(buf[: rn]) if err != nil { fmt.Println(err) panic(err) } if wn != rn { fmt.Println("err writing") panic("err writing") } } } /*用bufio库*/ func test_bufio() { ofile := "log.txt" fo, err := os.Open(ofile) if err != nil { panic(err) } defer fo.Close() r := bufio.NewReader(fo) cfile := "output.txt" fc, err := os.Create(cfile) if err != nil { panic(err) } defer fc.Close() w := bufio.NewWriter(fc) buf := make([]byte, 1024) for { fmt.Println("start") rn, err := r.Read(buf) if err != nil && err != io.EOF { panic(err) } if rn == 0 { break } wn, err := w.Write(buf[: rn]) if err != nil { panic(err) } if wn != rn { panic("err writing") } } err = w.Flush() if err != nil { panic(err) } } /*用ioutil库*/ func test_ioutil() { b, err := ioutil.ReadFile("log.txt") if err != nil { panic(err) } err = ioutil.WriteFile("out.txt", b, 0644) if err != nil { panic(err) } }