golang/go · error
error: cannot use -w with standard input
Error message
error: cannot use -w with standard input
What it means
Thrown by gofmtMain when no file/directory arguments are supplied (len(args)==0) and the -w (write) flag is set. With no arguments gofmt reads from standard input, and writing formatted output back over stdin is meaningless/impossible, so the combination is rejected up front.
Source
Thrown at src/cmd/gofmt/gofmt.go:410
if err != nil {
s.AddReport(fmt.Errorf("creating cpu profile: %s", err))
return
}
defer func() {
f.Close()
<-fdSem
}()
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
initParserMode()
initRewrite()
args := flag.Args()
if len(args) == 0 {
if *write {
s.AddReport(fmt.Errorf("error: cannot use -w with standard input"))
return
}
s.Add(0, func(r *reporter) error {
return processFile("<standard input>", nil, os.Stdin, r)
})
return
}
for _, arg := range args {
// Walk each given argument as a directory tree.
// If the argument is not a directory, it's always formatted as a Go file.
// If the argument is a directory, we walk it, ignoring non-Go files.
if err := filepath.WalkDir(arg, func(path string, d fs.DirEntry, err error) error {
switch {
case err != nil:
return err
case d.IsDir():
return nil // simply recurse into directoriesView on GitHub (pinned to b6b368adc5)
Solutions
- Pass the target files explicitly: `gofmt -w <files...>` or `gofmt -w .`.
- Drop -w when reading from stdin: `gofmt < foo.go` writes formatted output to stdout.
- If scripting, ensure the argument list is non-empty before adding -w.
Example fix
// before cat main.go | gofmt -w // after gofmt -w main.go
Defensive patterns
Strategy: validation
Validate before calling
if *write && len(flag.Args()) == 0 {
return errors.New("-w requires file/dir arguments; reading stdin is incompatible with -w")
} Prevention
- Always pass explicit files/dirs when using -w.
- When piping from stdin, omit -w and redirect stdout to the target file.
- In wrapper scripts, assert a non-empty argument list before forwarding -w.
When it happens
Trigger: Invoking `gofmt -w` with no positional arguments, or piping a file into gofmt while requesting in-place write, e.g. `cat foo.go | gofmt -w` or just `gofmt -w`.
Common situations: Forgetting to pass the file path after -w, copy-pasting a pipeline from a snippet that used -w, or scripts that conditionally drop the filename argument.
Related errors
- -C flag must be first flag on command line
- cannot combine -all and -short
- parse error
- tool %q is ambiguous; choose one of:
- no trace file supplied
AI-assisted analysis of golang/go@b6b368adc5 (2026-08-12).
Data as JSON: /api/errors/60441395910b79df.
Report an issue: GitHub.