CodeBlanks Logo Icon CodeBlanks

os.Stdin and os.Stdout

Learn the standard input and output streams.

os.Stdin and os.Stdout

Every process starts with three standard streams: os.Stdin (input), os.Stdout (normal output) and os.Stderr (errors and diagnostics). All are *os.File, so they are Readers and Writers.

fmt.Fprintln(os.Stdout, "sonuç: 42")
fmt.Fprintln(os.Stderr, "uyarı: önbellek boş")

Writing errors to stderr keeps the output clean when it is redirected with ./app > cikti.txt.

Exit codes

Command-line tools report success with the exit code: 0 means success, anything else an error. os.Exit(1) exits immediately without running defers. That's why the common pattern puts the work in a run() error function and only evaluates the result in main:

func main() {
    if err := run(os.Stdin, os.Stdout); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

Practice The run pattern

Write run(in io.Reader, out io.Writer) error: read all the input with io.ReadAll, convert it to upper case and write it to out. In main, call it with strings.NewReader("go") and os.Stdout.

Starter code

main.go
package main

import (
    "fmt"
    "io"
    "os"
    "strings"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "io"
    "os"
    "strings"
)

func run(in io.Reader, out io.Writer) error {
    b, err := io.ReadAll(in)
    if err != nil {
        return err
    }
    _, err = fmt.Fprintln(out, strings.ToUpper(string(b)))
    return err
}

func main() {
    if err := run(strings.NewReader("go"), os.Stdout); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

Expected output

GO

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In <code>./app | grep hata</code>, which stream does grep see?

  • Only stdout Correct answer
  • Only stderr
  • Both
  • Neither

Explanation: A pipe (|) connects only stdout; to pass stderr too, 2>&1 is added.

2 Error stream

Question
fmt.Fprintln(os.____, "dosya bulunamadı")
Answer
fmt.Fprintln(os.Stderr, "dosya bulunamadı")

Explanation: Error messages are written to os.Stderr, keeping them separate from normal output.

3 Stream and use

Term Meaning
os.Stdin Input
os.Stdout Result output
os.Stderr Errors and warnings
os.Exit(1) Failing exit

All lessons in Intermediate