golang/go · error

creating cpu profile: %s

Error message

creating cpu profile: %s

What it means

Thrown by gofmtMain when os.Create(*cpuprofile) fails while the -cpuprofile flag is set. The error is wrapped with the creating context and reported via s.AddReport; gofmt then returns without profiling. The underlying error is whatever os.Create returns (permission denied, no such directory, read-only fs).

Source

Thrown at src/cmd/gofmt/gofmt.go:393

	// call gofmtMain in a separate function
	// so that it can use defer and have them
	// run before the exit.
	gofmtMain(s)
	os.Exit(s.GetExitCode())
}

func gofmtMain(s *sequencer) {
	counter.Open()
	flag.Usage = usage
	flag.Parse()
	counter.Inc("gofmt/invocations")
	counter.CountFlags("gofmt/flag:", *flag.CommandLine)

	if *cpuprofile != "" {
		fdSem <- true
		f, err := os.Create(*cpuprofile)
		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

View on GitHub (pinned to b6b368adc5)

Solutions

  1. Create the parent directory: `mkdir -p $(dirname <path>)`.
  2. Check write permissions on the target directory and use a writable location like /tmp.
  3. Ensure <path> is a file path, not an existing directory.
  4. Drop -cpuprofile if profiling is not needed.

Example fix

// before
gofmt -cpuprofile=/nonexistent/cpu.prof .

// after
mkdir -p /tmp/prof && gofmt -cpuprofile=/tmp/prof/cpu.prof .
Defensive patterns

Strategy: validation

Validate before calling

profDir := filepath.Dir(*cpuprofile)
if info, err := os.Stat(profDir); err != nil || !info.IsDir() {
    return fmt.Errorf("cpuprofile dir %s missing or not a dir", profDir)
}

Prevention

When it happens

Trigger: Running `gofmt -cpuprofile=<path> ...` where <path> is in a non-existent directory, an unwritable location, a path that exists as a directory, or a filesystem that is read-only.

Common situations: Forgetting to create the output directory, pointing -cpuprofile at a path under /proc or another special filesystem, running as a user without write permission to the target, or specifying a directory path instead of a file path.

Related errors


AI-assisted analysis of golang/go@b6b368adc5 (2026-08-12). Data as JSON: /api/errors/612485e2da2a14a2. Report an issue: GitHub.