Writing standard output and error

Part of Golang Mastery course

~15 min read
Interactive
Hands-on
Beginner-friendly
  • each process has stdin, a stdout and stderr file descriptors. The standard approach is the use of stdout as a process output and stderr as process error output. As these are the file descriptors, the destination where the data is written could be anything, from the console to the socket.This recipe will show you how to write the stdout and stderr.

Create the stdouterr.go file with the following content:#

package main import ( "fmt" "io" "os" ) func main() { // Simply write string io.WriteString(os.Stdout, "This is string to standard output.\n") io.WriteString(os.Stderr, "This is string to standard error output.\n") // Stdout/err implements // writer interface buf := []byte{0xAF, 0xFF, 0xFE} for i := 0; i < 200; i++ { if _, e := os.Stdout.Write(buf); e != nil { panic(e) } } // The fmt package // could be used too fmt.Fprintln(os.Stdout, "\n") }

output:

sangam:golang-daily sangam$ go run stdouterr.go This is string to standard output. This is string to standard error output. ??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? sangam:golang-daily sangam$

How it works...#

  • As with the Stdin from the previous recipe, the Stdout and Stderr are the file descriptors. So these are implementing the Writer interface.

  • The preceding example shows a few ways of how to write into these via the io.WriteString function, with the use of the Writer API and by the fmt package and FprintXX functions.

Your Progress

80 of 103 modules
78%
Started78% Complete
Previous
SpaceComplete
Next