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

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

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?

  1. package main
  2. import "os"
  3. import "io"
  4. func main() {
  5. buf := make([]byte, 1024)
  6. var n int
  7. var err error
  8. for err != io.EOF {
  9. n, err = os.Stdin.Read(buf)
  10. if n > 0 {
  11. os.Stdout.Write(buf[0:n])
  12. }
  13. }
  14. }

答案1

得分: 11

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

示例:

  1. package main
  2. import (
  3. "os"
  4. "io"
  5. "log"
  6. )
  7. func main() {
  8. if _, err := io.Copy(os.Stdout, os.Stdin); err != nil {
  9. log.Fatal(err)
  10. }
  11. }
英文:

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

Example:

  1. package main
  2. import (
  3. "os"
  4. "io"
  5. "log"
  6. )
  7. func main() {
  8. if _, err := io.Copy(os.Stdout, os.Stdin); err != nil {
  9. log.Fatal(err)
  10. }
  11. }

答案2

得分: 5

例如,

  1. package main
  2. import (
  3. "io"
  4. "os"
  5. )
  6. func main() {
  7. io.Copy(os.Stdout, os.Stdin)
  8. }
英文:

For example,

  1. package main
  2. import (
  3. "io"
  4. "os"
  5. )
  6. func main() {
  7. io.Copy(os.Stdout, os.Stdin)
  8. }

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:

确定