Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write `cat` in Go using pipes

Tags:

unix

go

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])
        }
    }
}
like image 994
Sam Avatar asked Aug 03 '12 16:08

Sam


People also ask

How do I line a cat into a file?

To create a new file, use the cat command followed by the redirection operator ( > ) and the name of the file you want to create. Press Enter , type the text and once you are done, press the CRTL+D to save the file. If a file named file1. txt is present, it will be overwritten.

What is pipe in Golang?

A pipe is a form of redirection from one process to another process. It is a unidirectional data channel that can be used for interprocess communication. The io. Pipe function creates a synchronous in-memory pipe. It can be used to connect code expecting an io.

What is the use of pipe in Unix?

Pipe is used to combine two or more commands, and in this, the output of one command acts as input to another command, and this command's output may act as input to the next command and so on. It can also be visualized as a temporary connection between two or more commands/ programs/ processes.


2 Answers

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)
    }
}
like image 101
Staven Avatar answered Oct 17 '22 16:10

Staven


For example,

package main

import (
    "io"
    "os"
)

func main() {
    io.Copy(os.Stdout, os.Stdin)
}
like image 35
peterSO Avatar answered Oct 17 '22 16:10

peterSO