Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

← Go Index

🖥️ os — Operating system interface — files, env, process

Provides a platform-independent interface to OS functionality: file operations, environment variables, process control, and command-line arguments. The Go equivalent of C's unistd.h and stdlib.h combined.

Import: import "os" | Docs: pkg.go.dev/os

📋 Functions, Types & Constants

NameSignature / ValueDescription
os.Openfunc Open(name string) (*File, error)Open file for reading
os.Createfunc Create(name string) (*File, error)Create or truncate file for writing
os.OpenFilefunc OpenFile(name string, flag int, perm FileMode) (*File, error)Open with flags and permissions
os.ReadFilefunc ReadFile(name string) ([]byte, error)Read entire file into []byte (Go 1.16+)
os.WriteFilefunc WriteFile(name string, data []byte, perm FileMode) errorWrite []byte to file
os.Removefunc Remove(name string) errorDelete a file or empty directory
os.RemoveAllfunc RemoveAll(path string) errorDelete path and all children
os.Renamefunc Rename(oldpath, newpath string) errorRename / move a file
os.MkdirAllfunc MkdirAll(path string, perm FileMode) errorCreate directory tree
os.Mkdirfunc Mkdir(name string, perm FileMode) errorCreate single directory
os.Statfunc Stat(name string) (FileInfo, error)Return file metadata
os.Getenvfunc Getenv(key string) stringGet environment variable value
os.Setenvfunc Setenv(key, value string) errorSet environment variable
os.Argsvar Args []stringCommand-line arguments (Args[0] = program name)
os.Exitfunc Exit(code int)Terminate with exit code
os.Getwdfunc Getwd() (dir string, err error)Return current working directory
os.Chdirfunc Chdir(dir string) errorChange current working directory
os.Stdin*os.FileStandard input file descriptor
os.Stdout*os.FileStandard output file descriptor
os.Stderr*os.FileStandard error file descriptor
os.O_RDONLYconst = 0Open flag: read only
os.O_WRONLYconst = 1Open flag: write only
os.O_RDWRconst = 2Open flag: read and write
os.O_CREATEconstOpen flag: create if not exists
os.O_APPENDconstOpen flag: append to file
os.O_TRUNCconstOpen flag: truncate on open

💡 Example Program

Save as main.go inside any directory and run with go run main.go. No extra packages to install — all standard library.

package main

import (
    "fmt"
    "os"
)

func main() {
    // Command-line args
    fmt.Println("Program:", os.Args[0])
    if len(os.Args) > 1 {
        fmt.Println("Args:", os.Args[1:])
    }

    // Environment variable
    home := os.Getenv("HOME")
    fmt.Println("HOME:", home)

    // Write a file
    err := os.WriteFile("hello.txt", []byte("Hello from Go!\n"), 0644)
    if err != nil {
        fmt.Fprintln(os.Stderr, "Write error:", err)
        os.Exit(1)
    }

    // Read it back
    data, err := os.ReadFile("hello.txt")
    if err != nil {
        fmt.Fprintln(os.Stderr, "Read error:", err)
        os.Exit(1)
    }
    fmt.Print("File contents: ", string(data))

    // File metadata
    info, _ := os.Stat("hello.txt")
    fmt.Printf("File size: %d bytes\n", info.Size())

    // Cleanup
    os.Remove("hello.txt")
    fmt.Println("Done.")
}
// go run main.go

← fmt  |  🏠 Index  |  io →