golang IO COPY

来源:转载

使用golang实现 IO copy,测试程序如下:

package mainimport ("fmt""io""os""syscall")func main() {var errCh chan errorerrCh = 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.Writervar in io.Readerin = 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.Writervar in io.Readerout = 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 = ewbreak}if nr != nw {err = ErrShortWritebreak}}if er == EOF {break}if er != nil {err = erbreak}}return written, err}

阻塞式的从src输入流读数据到dst输出流



分享给朋友:
您可能感兴趣的文章:
随机阅读: