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])
}
}
}
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.
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.
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.
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)
}
}
For example,
package main
import (
"io"
"os"
)
func main() {
io.Copy(os.Stdout, os.Stdin)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With