Golang File I/O & OS Interactions Quiz

Golang
0 Passed
0% acceptance

35 comprehensive questions on Golang's file I/O and OS interaction capabilities, covering file reading/writing, os package usage, streams & buffers, directory operations, and environment variables — with 18 code examples demonstrating practical file and OS operations.

35 Questions
~70 minutes
1

Question 1

How do you read an entire file in Go?

go
data, err := os.ReadFile("file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(data))
A
Use os.ReadFile() to read entire file into []byte
B
Use os.Open() and read line by line
C
Use bufio.Scanner
D
Cannot read entire file
2

Question 2

How do you write to a file in Go?

go
data := []byte("Hello, World!")
err := os.WriteFile("output.txt", data, 0644)
if err != nil {
    log.Fatal(err)
}
A
Use os.WriteFile() with data, filename, and permissions
B
Use fmt.Println to file
C
Use os.Create and write manually
D
Cannot write to files
3

Question 3

What is the difference between os.Open and os.OpenFile?

go
file, err := os.Open("file.txt")  // Read-only

file, err := os.OpenFile("file.txt", os.O_RDWR|os.O_CREATE, 0644)  // Read/write
A
os.Open is read-only, os.OpenFile allows specifying flags and permissions
B
No difference
C
os.OpenFile is deprecated
D
os.Open allows writing
4

Question 4

How do you read a file line by line?

go
file, err := os.Open("file.txt")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

scanner := bufio.NewScanner(file)
for scanner.Scan() {
    fmt.Println(scanner.Text())
}

if err := scanner.Err(); err != nil {
    log.Fatal(err)
}
A
Use bufio.Scanner with file reader
B
Use os.ReadFile and split by \n
C
Use io.ReadAll
D
Cannot read line by line
5

Question 5

How do you create a directory?

go
err := os.Mkdir("newdir", 0755)
if err != nil {
    log.Fatal(err)
}

// Create nested directories
err = os.MkdirAll("parent/child/grandchild", 0755)
A
Use os.Mkdir() for single directory, os.MkdirAll() for nested
B
Use os.Create
C
Use os.WriteFile
D
Cannot create directories
6

Question 6

How do you list directory contents?

go
files, err := os.ReadDir("mydir")
if err != nil {
    log.Fatal(err)
}

for _, file := range files {
    fmt.Println(file.Name(), file.IsDir())
}
A
Use os.ReadDir() to get []os.DirEntry
B
Use os.Open and read
C
Use filepath.Walk
D
Cannot list directories
7

Question 7

How do you get environment variables?

go
value := os.Getenv("HOME")
fmt.Println("Home:", value)

// Get all environment variables
for _, env := range os.Environ() {
    fmt.Println(env)
}
A
Use os.Getenv() for single variable, os.Environ() for all
B
Use os.Args
C
Use runtime variables
D
Cannot get environment variables
8

Question 8

How do you set environment variables?

go
err := os.Setenv("MY_VAR", "my_value")
if err != nil {
    log.Fatal(err)
}

// Check if set
fmt.Println(os.Getenv("MY_VAR"))
A
Use os.Setenv() to set environment variables
B
Use os.Getenv
C
Use global variables
D
Cannot set environment variables
9

Question 9

What is buffered I/O in Go?

go
file, _ := os.Open("large.txt")
defer file.Close()

bufferedReader := bufio.NewReader(file)
data, err := bufferedReader.ReadString('\n')

// Buffered writer
file, _ = os.Create("output.txt")
bufferedWriter := bufio.NewWriter(file)
bufferedWriter.WriteString("Hello")
bufferedWriter.Flush()
A
Using bufio.Reader/Writer to buffer reads/writes for efficiency
B
Reading entire files
C
Using os.ReadFile
D
No buffering in Go
10

Question 10

How do you copy a file in Go?

go
srcFile, err := os.Open("source.txt")
if err != nil {
    log.Fatal(err)
}
defer srcFile.Close()

dstFile, err := os.Create("dest.txt")
if err != nil {
    log.Fatal(err)
}
defer dstFile.Close()

_, err = io.Copy(dstFile, srcFile)
if err != nil {
    log.Fatal(err)
}
A
Use io.Copy() to copy between readers and writers
B
Use os.ReadFile and os.WriteFile
C
Use bufio.Copy
D
Cannot copy files
11

Question 11

How do you check if a file exists?

go
if _, err := os.Stat("file.txt"); os.IsNotExist(err) {
    fmt.Println("File does not exist")
} else if err != nil {
    log.Fatal(err)
} else {
    fmt.Println("File exists")
}
A
Use os.Stat() and check os.IsNotExist(err)
B
Use os.Open
C
Use os.ReadFile
D
Cannot check file existence
12

Question 12

How do you get file permissions?

go
info, err := os.Stat("file.txt")
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Permissions: %s\n", info.Mode())
fmt.Printf("Is executable: %t\n", info.Mode().Perm()&0111 != 0)
A
Use os.Stat() to get FileInfo, then info.Mode().Perm()
B
Use os.Open
C
Use os.ReadFile
D
Cannot get permissions
13

Question 13

How do you change file permissions?

go
err := os.Chmod("file.txt", 0644)
if err != nil {
    log.Fatal(err)
}

// Change owner
err = os.Chown("file.txt", uid, gid)
A
Use os.Chmod() to change permissions, os.Chown() for ownership
B
Use os.WriteFile
C
Use os.Create
D
Cannot change permissions
14

Question 14

How do you work with temporary files?

go
tmpFile, err := os.CreateTemp("", "prefix-*.txt")
if err != nil {
    log.Fatal(err)
}
defer os.Remove(tmpFile.Name())  // Clean up

defer tmpFile.Close()

tmpFile.WriteString("temporary data")

// Use tmpFile.Name() for the path
A
Use os.CreateTemp() to create temporary files with auto-generated names
B
Use os.Create with random names
C
Use os.WriteFile
D
Cannot create temporary files
15

Question 15

How do you read from standard input?

go
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Enter text: ")
scanner.Scan()
text := scanner.Text()
fmt.Println("You entered:", text)
A
Use bufio.Scanner with os.Stdin
B
Use os.ReadFile
C
Use fmt.Scan
D
Cannot read from stdin
16

Question 16

How do you write to standard output/error?

go
fmt.Fprintln(os.Stdout, "This goes to stdout")
fmt.Fprintln(os.Stderr, "This goes to stderr")

// Or use os.Stdout/Stderr directly
os.Stdout.WriteString("Direct write\n")
A
Use os.Stdout and os.Stderr with fmt or direct writes
B
Use fmt.Print
C
Use os.WriteFile
D
Cannot write to stdout/stderr
17

Question 17

How do you handle file paths cross-platform?

go
import "path/filepath"

// Join paths
path := filepath.Join("home", "user", "file.txt")

// Get directory and filename
fmt.Println(filepath.Dir(path))   // home/user
fmt.Println(filepath.Base(path))  // file.txt

// Check if absolute
fmt.Println(filepath.IsAbs(path))
A
Use path/filepath package for cross-platform path operations
B
Use string concatenation
C
Use os.PathSeparator manually
D
No cross-platform paths
18

Question 18

How do you walk a directory tree?

go
err := filepath.Walk("rootdir", func(path string, info os.FileInfo, err error) error {
    if err != nil {
        return err
    }
    
    if info.IsDir() {
        fmt.Println("Directory:", path)
    } else {
        fmt.Println("File:", path)
    }
    
    return nil
})
A
Use filepath.Walk() with a callback function
B
Use os.ReadDir recursively
C
Use os.Open
D
Cannot walk directories
19

Question 19

How do you handle file locking?

go
file, err := os.OpenFile("file.txt", os.O_RDWR, 0644)
if err != nil {
    log.Fatal(err)
}
defer file.Close()

// Try to lock (Unix only)
err = syscall.Flock(int(file.Fd()), syscall.LOCK_EX)
if err != nil {
    log.Fatal(err)
}
defer syscall.Flock(int(file.Fd()), syscall.LOCK_UN)

// Now safe to read/write
A
Use syscall.Flock() for advisory locking (Unix systems)
B
Use os.Lock
C
Use sync.Mutex
D
Cannot lock files
20

Question 20

How do you read environment variables with defaults?

go
port := os.Getenv("PORT")
if port == "" {
    port = "8080"  // Default value
}

// Or using a helper function
func getEnv(key, defaultValue string) string {
    if value := os.Getenv(key); value != "" {
        return value
    }
    return defaultValue
}

port = getEnv("PORT", "8080")
A
Check if os.Getenv() returns empty string, provide default
B
Use os.Getenv with default parameter
C
Use global defaults
D
Cannot provide defaults
21

Question 21

How do you append to a file?

go
file, err := os.OpenFile("log.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
    log.Fatal(err)
}
defer file.Close()

_, err = file.WriteString("New log entry\n")
if err != nil {
    log.Fatal(err)
}
A
Use os.OpenFile with O_APPEND flag
B
Use os.WriteFile
C
Use os.Create
D
Cannot append to files
22

Question 22

How do you get the current working directory?

go
cwd, err := os.Getwd()
if err != nil {
    log.Fatal(err)
}
fmt.Println("Current directory:", cwd)
A
Use os.Getwd() to get current working directory
B
Use os.Args[0]
C
Use filepath.Abs
D
Cannot get current directory
23

Question 23

How do you change the current working directory?

go
err := os.Chdir("/tmp")
if err != nil {
    log.Fatal(err)
}

// Verify
cwd, _ := os.Getwd()
fmt.Println("New CWD:", cwd)
A
Use os.Chdir() to change current working directory
B
Use os.Setwd
C
Use filepath.Chdir
D
Cannot change directory
24

Question 24

How do you handle large files efficiently?

go
file, err := os.Open("large.txt")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

buffer := make([]byte, 4096)  // 4KB buffer
for {
    n, err := file.Read(buffer)
    if n > 0 {
        // Process buffer[:n]
        processChunk(buffer[:n])
    }
    if err == io.EOF {
        break
    }
    if err != nil {
        log.Fatal(err)
    }
}
A
Read in chunks using a buffer, don't load entire file into memory
B
Use os.ReadFile always
C
Use bufio with small buffer
D
Cannot handle large files
25

Question 25

How do you create a pipe for inter-process communication?

go
r, w, err := os.Pipe()
if err != nil {
    log.Fatal(err)
}

go func() {
    defer w.Close()
    w.WriteString("Hello from child")
}()

buffer := make([]byte, 100)
n, err := r.Read(buffer)
fmt.Println(string(buffer[:n]))
r.Close()
A
Use os.Pipe() to create connected reader/writer pair
B
Use io.Pipe
C
Use channels
D
Cannot create pipes
26

Question 26

How do you handle file truncation?

go
file, err := os.OpenFile("file.txt", os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
    log.Fatal(err)
}
defer file.Close()

// File is now empty
file.WriteString("New content")
A
Use O_TRUNC flag in os.OpenFile to truncate existing files
B
Use os.Truncate
C
Use os.Remove and os.Create
D
Cannot truncate files
27

Question 27

How do you read environment variables as integers?

go
timeoutStr := os.Getenv("TIMEOUT")
if timeoutStr == "" {
    timeoutStr = "30"
}

timeout, err := strconv.Atoi(timeoutStr)
if err != nil {
    log.Fatal("Invalid TIMEOUT value:", err)
}

fmt.Println("Timeout:", timeout)
A
Use os.Getenv then strconv.Atoi to parse as integer
B
Use os.GetenvInt
C
Use fmt.Sscanf
D
Cannot parse env vars
28

Question 28

How do you safely remove files and directories?

go
err := os.Remove("file.txt")  // Remove file

err = os.RemoveAll("directory")  // Remove directory and contents

// Check if exists before removing
if _, err := os.Stat("file.txt"); !os.IsNotExist(err) {
    err = os.Remove("file.txt")
}
A
Use os.Remove() for files, os.RemoveAll() for directories
B
Use os.Delete
C
Use os.Rm
D
Cannot remove files
29

Question 29

How do you handle symbolic links in Go?

go
// Read link target
linkTarget, err := os.Readlink("mylink")

// Check if file is a symlink
info, err := os.Lstat("file")
if info.Mode() & os.ModeSymlink != 0 {
    fmt.Println("Is a symlink")
}

// Create symlink
err = os.Symlink("target", "linkname")
A
Use os.Readlink(), os.Lstat(), os.Symlink() for symlink operations
B
Use os.Stat
C
Use filepath.EvalSymlinks
D
Cannot handle symlinks
30

Question 30

How do you implement a simple file-based logger?

go
type FileLogger struct {
    file *os.File
}

func NewFileLogger(filename string) (*FileLogger, error) {
    file, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        return nil, err
    }
    return &FileLogger{file: file}, nil
}

func (l *FileLogger) Log(message string) {
    timestamp := time.Now().Format(time.RFC3339)
    l.file.WriteString(fmt.Sprintf("[%s] %s\n", timestamp, message))
}

func (l *FileLogger) Close() {
    l.file.Close()
}
A
Create a struct with *os.File, use os.OpenFile with O_APPEND, implement logging methods
B
Use fmt.Printf to file
C
Use log package with file
D
Cannot implement file logger
31

Question 31

How do you read configuration from environment variables?

go
type Config struct {
    Port     int
    Database string
    Debug    bool
}

func loadConfig() Config {
    port, _ := strconv.Atoi(getEnv("PORT", "8080"))
    database := getEnv("DATABASE", "postgres://localhost")
    debug := getEnv("DEBUG", "false") == "true"
    
    return Config{
        Port:     port,
        Database: database,
        Debug:    debug,
    }
}

func getEnv(key, defaultValue string) string {
    if value := os.Getenv(key); value != "" {
        return value
    }
    return defaultValue
}
A
Create Config struct, read env vars with defaults, parse types as needed
B
Use global variables
C
Use JSON files
D
Cannot read config from env
32

Question 32

How do you handle file I/O errors properly?

go
func readFile(filename string) ([]byte, error) {
    data, err := os.ReadFile(filename)
    if err != nil {
        if os.IsNotExist(err) {
            return nil, fmt.Errorf("file %s does not exist", filename)
        }
        if os.IsPermission(err) {
            return nil, fmt.Errorf("permission denied reading %s", filename)
        }
        return nil, fmt.Errorf("error reading %s: %w", filename, err)
    }
    return data, nil
}
A
Check specific error types with os.IsNotExist, os.IsPermission, etc., wrap errors with context
B
Ignore errors
C
Use panic
D
Cannot handle I/O errors
33

Question 33

How do you implement a file watcher?

go
func watchFile(filename string) {
    lastMod := time.Time{}
    
    for {
        info, err := os.Stat(filename)
        if err != nil {
            log.Println("Error stat'ing file:", err)
            time.Sleep(time.Second)
            continue
        }
        
        if info.ModTime().After(lastMod) {
            fmt.Println("File changed!")
            lastMod = info.ModTime()
            // Handle file change
        }
        
        time.Sleep(time.Second)
    }
}
A
Poll file modification time with os.Stat in a loop
B
Use os.WatchFile
C
Use inotify
D
Cannot watch files
34

Question 34

How do you work with binary files?

go
type Header struct {
    Magic   uint32
    Version uint16
    Count   uint32
}

func readBinaryFile(filename string) (*Header, error) {
    file, err := os.Open(filename)
    if err != nil {
        return nil, err
    }
    defer file.Close()
    
    var header Header
    err = binary.Read(file, binary.LittleEndian, &header)
    if err != nil {
        return nil, err
    }
    
    return &header, nil
}
A
Use encoding/binary package to read/write structured binary data
B
Use os.ReadFile and cast
C
Use bufio.Scanner
D
Cannot work with binary files
35

Question 35

What is the most important principle for file I/O in Go?

A
Always close files with defer, handle errors properly, use appropriate buffer sizes, prefer streaming for large files, use cross-platform path handling
B
Never close files
C
Use global file handles
D
Ignore errors

QUIZZES IN Golang