os库提供文件目录操作,如创建、读写、删除文件,遍历目录等,需用defer关闭文件并处理错误,filepath.Walk可递归遍历目录,os.Stat获取文件信息,正确设置文件权限确保安全。

Golang 的
os
os
文件操作:
os.Create(name string) (*os.File, error)
os.File
error
os.Open(name string) (*os.File, error)
os.OpenFile(name string, flag int, perm os.FileMode) (*os.File, error)
os.O_RDWR
os.O_CREATE
file.Close() error
io.Copy(dst io.Writer, src io.Reader) (written int64, err error)
src
dst
os.Remove(name string) error
目录操作:
os.Mkdir(name string, perm os.FileMode) error
os.MkdirAll(path string, perm os.FileMode) error
os.RemoveAll(path string) error
os.Rename(oldpath, newpath string) error
os.Chdir(dir string) error
os.Getwd() (string, error)
os.ReadDir(name string) ([]fs.DirEntry, error)
fs.DirEntry
其他:
立即学习“go语言免费学习笔记(深入)”;
os.Stat(name string) (fs.FileInfo, error)
os.IsExist(err error) bool
os.IsNotExist(err error) bool
如何安全地进行文件读写操作?
在进行文件读写操作时,安全性至关重要。一个常见的错误是忘记关闭文件,导致资源泄漏。可以使用
defer file.Close()
package main
import (
"fmt"
"io"
"os"
)
func main() {
file, err := os.Create("example.txt")
if err != nil {
fmt.Println("Unable to create file:", err)
return
}
defer file.Close() // 确保文件关闭
_, err = io.WriteString(file, "Hello, World!")
if err != nil {
fmt.Println("Unable to write to file:", err)
return
}
fmt.Println("File created and written successfully.")
// 示例:读取文件
readFile, err := os.Open("example.txt")
if err != nil {
fmt.Println("Unable to open file for reading:", err)
return
}
defer readFile.Close()
data := make([]byte, 64) // 读取缓冲区
count, err := readFile.Read(data)
if err != nil && err != io.EOF { // io.EOF 是文件结束的标志
fmt.Println("Unable to read file:", err)
return
}
fmt.Printf("Read %d bytes: %s\n", count, string(data[:count]))
}错误处理也至关重要。每次调用
os
error
如何遍历目录及其子目录?
filepath.Walk
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
root := "." // 当前目录
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
fmt.Printf("prevent panic by handling failure accessing a path %q: %v\n", path, err)
return err
}
fmt.Printf("visited file or dir: %q\n", path)
return nil
})
if err != nil {
fmt.Printf("error walking the path %q: %v\n", root, err)
return
}
}filepath.Walk
os.FileInfo
如何获取文件信息?
os.Stat
fs.FileInfo
package main
import (
"fmt"
"os"
)
func main() {
fileInfo, err := os.Stat("example.txt")
if err != nil {
fmt.Println("Error getting file info:", err)
return
}
fmt.Println("File Name:", fileInfo.Name())
fmt.Println("File Size:", fileInfo.Size(), "bytes")
fmt.Println("Is Directory:", fileInfo.IsDir())
fmt.Println("Last Modified:", fileInfo.ModTime())
fmt.Println("Permissions:", fileInfo.Mode())
}fs.FileInfo
Name()
Size()
IsDir()
ModTime()
Mode()
理解文件权限(
os.FileMode
0644
0755
os
以上就是Golang os库文件与目录操作方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号