使用golang实现 IO copy,测试程序如下:
package main import ( "fmt" "io" "os" "syscall" ) func main() { var errCh chan error errCh = Go(func() error { return test_stdout() }) if err := <-errCh; err != nil { fmt.Printf("End io_copy: %s\n", err) //return err } } //异步执行 func Go(f func() error) chan error { ch := make(chan error, 1) go func() { ch <- f() }() return ch } //输入流复制到文件里面 func test_stdin() error { var out io.Writer var in io.Reader in = os.NewFile(uintptr(syscall.Stdin), "/dev/stdin") out, _ = os.OpenFile("D:/golang/project/docker/env.txt", os.O_RDWR, 0666) n, err := io.Copy(out, in) fmt.Printf("\n write %d err %v \n", n, err) return err } //文件里面复制到输出流 func test_stdout() error { var out io.Writer var in io.Reader out = os.NewFile(uintptr(syscall.Stdout), "/dev/stdout") in, _ = os.OpenFile("D:/golang/project/docker/env.txt", os.O_RDWR, 0666) n, err := io.Copy(out, in) fmt.Printf("\n write %d err %v \n", n, err) return err }
再看看io.Copy的代码:
func Copy(dst Writer, src Reader) (written int64, err error) { // If the reader has a WriteTo method, use it to do the copy. // Avoids an allocation and a copy. if wt, ok := src.(WriterTo); ok { return wt.WriteTo(dst) } // Similarly, if the writer has a ReadFrom method, use it to do the copy. if rt, ok := dst.(ReaderFrom); ok { return rt.ReadFrom(src) } buf := make([]byte, 32*1024) for { nr, er := src.Read(buf) if nr > 0 { nw, ew := dst.Write(buf[0:nr]) if nw > 0 { written += int64(nw) } if ew != nil { err = ew break } if nr != nw { err = ErrShortWrite break } } if er == EOF { break } if er != nil { err = er break } } return written, err }
阻塞式的从src输入流读数据到dst输出流
有疑问加站长微信联系(非本文作者)