如何使用管道在Go中编写`cat`命令

huangapple go评论74阅读模式
英文:

How to write `cat` in Go using pipes

问题

我有一个下面的Unix工具cat的实现。它从os.Stdin读取一定数量的字节到缓冲区,然后将这些字节写入os.Stdout。有没有办法跳过缓冲区,直接将Stdin管道传输到Stdout

英文:

I have an implementation of the Unix tool cat below. It reads a number of bytes from os.Stdin into a buffer, then writes those bytes out to os.Stdout. Is there a way I can skip the buffer and just pipe Stdin directly to Stdout?

package main

import "os"
import "io"

func main() {
	buf := make([]byte, 1024)

	var n int
	var err error
	for err != io.EOF {
		n, err = os.Stdin.Read(buf)

		if n > 0 {
			os.Stdout.Write(buf[0:n])
		}
	}
}

答案1

得分: 11

你可以使用io.Copy() (文档在这里)

示例:

package main

import (
	"os"
	"io"
	"log"
)

func main() {
	if _, err := io.Copy(os.Stdout, os.Stdin); err != nil {
		log.Fatal(err)
	}
}
英文:

You can use io.Copy() (Documentation here)

Example:

package main

import (
	"os"
	"io"
	"log"
)

func main() {
	if _, err := io.Copy(os.Stdout, os.Stdin); err != nil {
		log.Fatal(err)
	}
}

答案2

得分: 5

例如,

package main

import (
    "io"
    "os"
)

func main() {
    io.Copy(os.Stdout, os.Stdin)
}
英文:

For example,

package main

import (
	"io"
	"os"
)

func main() {
	io.Copy(os.Stdout, os.Stdin)
}

huangapple
  • 本文由 发表于 2012年8月4日 00:28:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/11799692.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定