How to use the os package in golang?
In Go language, the os package is used to manipulate operating system functionalities such as file and directory operations, environment variables, and processes. Below are some common examples of how to use the os package.
- Import the os package.
import "os"
- Get the current working directory:
dir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
fmt.Println("当前工作目录:", dir)
- Create a directory:
err := os.Mkdir("mydir", 0755)
if err != nil {
log.Fatal(err)
}
- Create a file.
file, err := os.Create("myfile.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
- Open the file:
file, err := os.Open("myfile.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
- Read the file contents:
data := make([]byte, 100)
count, err := file.Read(data)
if err != nil {
log.Fatal(err)
}
fmt.Printf("读取 %d 字节的数据: %q\n", count, data[:count])
- Write to file:
data := []byte("Hello, World!")
count, err := file.Write(data)
if err != nil {
log.Fatal(err)
}
fmt.Printf("写入 %d 字节的数据\n", count)
- Delete a file or directory.
err := os.Remove("myfile.txt")
if err != nil {
log.Fatal(err)
}
These are just some basic examples of how to use the os package. The os package also offers many other functions such as file renaming, changing file permissions, getting and setting environment variables, and managing processes. You can refer to the official documentation for more usage information based on your specific needs.