Chapter 12: Files and Systems

Introduksyon

Ang File I/O kay parte na sa kinabuhi sa programmer. Kung magbasa ka ug files, magsulat, mag-ayos ug directories, o mag-handle ug command-line args — ang Go os ug io packages kay imong bestfriend. Clean API, walay sakit sa ulo.

Filesystem

Ang Go os package kay platform-independent — sa Windows, Mac, o Linux, parehas rag gamit:

import "os"

// Create directory
os.Mkdir("mydir", 0755)
os.MkdirAll("a/b/c", 0755)  // creates parents too

// Remove
os.Remove("file.txt")
os.RemoveAll("mydir")       // recursive

// Rename
os.Rename("old.txt", "new.txt")

// Check existence
_, err := os.Stat("file.txt")
if os.IsNotExist(err) {
    fmt.Println("file does not exist")
}

File Permissions

Ang file permissions sa Go kay Unix-style (octal). Gamit ug os.FileMode:

// Common permissions
0644  // owner read/write, group/others read
0755  // owner read/write/exec, group/others read/exec
0600  // owner read/write only

// Set permissions when creating
f, _ := os.Create("file.txt")   // default 0666 (before umask)
f.Close()

os.Chmod("file.txt", 0644)     // change permissions

// Check permissions
info, _ := os.Stat("file.txt")
fmt.Println(info.Mode())       // -rw-r--r--

Flags and Arguments

Access command-line arguments gamit os.Args. Ang first element (os.Args[0]) kay automatic na nga program name:

import (
    "fmt"
    "os"
)

func main() {
    if len(os.Args) < 2 {
        fmt.Println("Usage: myapp ")
        os.Exit(1)
    }
    name := os.Args[1]
    fmt.Println("Hello,", name)
}

Para complex flag parsing (kanang may --name o -v), gamit ang flag package. Dili nang manual.

Signals

Handle OS signals (SIGINT, SIGTERM) para graceful shutdown — dili maguba kalit:

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"
)

func main() {
    sigCh := make(chan os.Signal, 1)
    signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)

    fmt.Println("Waiting for signal...")
    sig := <-sigCh
    fmt.Println("Received signal:", sig)
    fmt.Println("Shutting down gracefully...")
}

Exercise 12.01: Simulating Cleanup

Goal: Maghimo ug program nga mag-create ug temp file, mag-work, ug mag-cleanup pag naay interrupt.

package main

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"
)

func main() {
    tmpFile, _ := os.CreateTemp("", "example-*.txt")
    fmt.Println("Created:", tmpFile.Name())
    defer os.Remove(tmpFile.Name())
    defer tmpFile.Close()

    sigCh := make(chan os.Signal, 1)
    signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)

    fmt.Println("Press Ctrl+C to quit...")
    <-sigCh
    fmt.Println("\nCleaning up...")
}

Creating and Writing to Files

Magsulat ug data sa files — pwede all at once gamit os.WriteFile, line by line gamit os.Create, or buffered for performance:

// Simple: write all at once
data := []byte("Hello, Go!\n")
os.WriteFile("hello.txt", data, 0644)

// Line by line
f, _ := os.Create("lines.txt")
defer f.Close()
for i := 1; i <= 5; i++ {
    fmt.Fprintf(f, "Line %d\n", i)
}

// Buffered writing for performance
buf := bufio.NewWriter(f)
buf.WriteString("buffered content\n")
buf.Flush()

Reading the Whole File at Once

Basaha ang tibuok file gamit os.ReadFile (dali ra) or line by line gamit scanner (kung daghan kaayo lines):

// Read entire file
data, _ := os.ReadFile("hello.txt")
fmt.Println(string(data))

// Read line by line
f, _ := os.Open("hello.txt")
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
    fmt.Println(">", scanner.Text())
}

Exercise 12.02: Backing Up Files

Goal: Basaha ang file ug paghimo ug backup copy na ".bak" extension. Safety first.

package main

import (
    "fmt"
    "os"
)

func main() {
    src := "data.txt"
    dst := src + ".bak"

    data, err := os.ReadFile(src)
    if err != nil {
        fmt.Println("Error reading:", err)
        return
    }

    err = os.WriteFile(dst, data, 0644)
    if err != nil {
        fmt.Println("Error writing:", err)
        return
    }
    fmt.Println("Backup created:", dst)
}

CSV

Ang Go encoding/csv package kay ready na para magbasa ug magsulat ug CSV files — no need third-party libraries:

import "encoding/csv"

// Reading
f, _ := os.Open("data.csv")
defer f.Close()
r := csv.NewReader(f)
records, _ := r.ReadAll()
for _, row := range records {
    fmt.Println(row)
}

// Writing
f, _ = os.Create("output.csv")
defer f.Close()
w := csv.NewWriter(f)
w.Write([]string{"Name", "Age", "City"})
w.Write([]string{"Alice", "30", "Tokyo"})
w.Flush()

Activity 12.01: Parsing Bank Transaction Files

Goal: I-parse ang CSV file sa bank transactions, kwentaha ang total, ug magsulat ug summary. Accounting na ni level.

package main

import (
    "encoding/csv"
    "fmt"
    "os"
    "strconv"
)

type Transaction struct {
    Date        string
    Description string
    Amount      float64
}

func main() {
    f, _ := os.Open("transactions.csv")
    defer f.Close()

    r := csv.NewReader(f)
    records, _ := r.ReadAll()

    var total float64
    var transactions []Transaction

    for i, row := range records {
        if i == 0 { continue }  // skip header
        amount, _ := strconv.ParseFloat(row[2], 64)
        transactions = append(transactions, Transaction{
            Date: row[0], Description: row[1], Amount: amount,
        })
        total += amount
    }

    fmt.Printf("Processed %d transactions\n", len(transactions))
    fmt.Printf("Total: $%.2f\n", total)

    out, _ := os.Create("summary.txt")
    defer out.Close()
    fmt.Fprintf(out, "Total transactions: %d\n", len(transactions))
    fmt.Fprintf(out, "Total amount: $%.2f\n", total)
}

Summary