Skip to content

os - Go 中 os 标准库的使用

Updated View as Markdown

Intro

os 包是 Go 语言标准库的重要组成部分,提供了与操作系统交互的跨平台接口。它封装了底层系统调用,使开发者能够方便地访问和操作操作系统资源。

文件操作

创建空文件

package main

import (
    "fmt"
    "os"
)

func main() {
    file, err := os.Create("example.txt")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer file.Close() // 注意 Close

    fmt.Println("Files Created.")
}

读取文件

// You can edit this code!
// Click here and start typing.
package main

import (
	"fmt"
	"log"
	"os"
)

func main() {

	file, err := os.Open("example.txt") // For read access.
	if err != nil {
		log.Fatal(err)
	}

	data := make([]byte, 100) // 切片类型 (请参阅: http://notes.linserin.work/go/01-abc/variable/#%E5%88%87%E7%89%87slice )

	count, err := file.Read(data)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("read %d bytes: %q\n", count, data[:count])
	defer file.Close() // 完成后 main 在 return 之前把文件 Close.
}

环境变量

读取与设置

// You can edit this code!
// Click here and start typing.
package main

import (
	"fmt"
	"log"
	"os"
)

func main() {
	// Get an environment variable.
	path := os.Getenv("PATH")
	fmt.Println("Path:", path)

	// Set an environment variable.
	err := os.Setenv("MY_VAR", "my_value")
	if err != nil {
		log.Fatal(err)
	}

	value := os.Getenv("MY_VAR")
	fmt.Println("MY_VAR:", value)
}

Navigation

Type to search…

↑↓ navigate↵ selectEsc close