File 读取文件操作
ioutil.ReadFile()
f, err := ioutil.ReadFile("helloworld.txt")
if err != nil {
fmt.Println("read fail", err)
}
fmt.Print(string(f))
ReadFile读取以filename命名的文件并返回内容。一个成功的调用返回 err == nil
,而不是err == EOF
。因为ReadFile读取整个文件,所以它不会将Read中的EOF视为要报告的错误。已弃用:从Go 1.16开始,这个函数简单地调用os.ReadFile。
file, err := os.ReadFile("helloworld.txt")
if err != nil {
os.Exit(1)
}
os.Stdout.Write(file)
在使用模版的时候,使用os.Stdout,只能输出到控制台。
File 文件写入操作
file.WriteString()
file, err := os.OpenFile("helloworld.txt", syscall.O_RDWR|syscall.O_CREAT, 0)
if err != nil {
os.Exit(1)
}
defer file.Close()
file.WriteString("hello world. Nice to see you.")
func Rename 修改路径 / 文件名称
func Rename(oldpath, newpath string) error
Rename renames (moves) oldpath to newpath. If newpath already exists and is not a directory, Rename replaces it. OS-specific restrictions may apply when oldpath and newpath are in different directories. If there is an error, it will be of type *LinkError.
Windows os 执行 cmd 命令
首先引入 os/exec 包
import "os/exec"
创建执行函数
Command(name string, args …string) *Cmd
这里name就是我们的命令/可执行文件,例如如果要执行cmd命令,这个name就是"cmd";如果要执行bash命令,那么这个name就是"/bin/bash",而后面的参数args可以一个一个输入。