Golang file directory creation, reading, and deletion operations

Creation and deletion of file directories

package main

import(
    "fmt"
    "os"
)

func main(){
    //创建目录和权限
    os.Mkdir("./benben",0777)
    //创建多级目录和设置权限
    os.MkdirAll("./benben/test",0777)
    //删除目录
    err:=os.Remove("./benben")
    if err!=nil{
        fmt.Println(err)
    }
    //删除多级目录
    os.RemoveAll("./benben")
}

file creation

package main

import (
    "os"
    "fmt"
)

func main(){
    //文件的创建,Create会根据传入的文件名创建文件,默认权限是0666
    file,err:=os.Create("a.txt")
    if err!=nil{
        fmt.Println(err)
    }
    defer file.Close()
}

File Opening and Closing The file opening and closing related functions are demonstrated in the file reading and writing example.

There are several ways to read and write files: Method 1: Use os.Open() and ioutil.ReadAll() methods

package main

func main(){
    //打开文件
    file,err:=os.Open("a.txt")
    if err !=nil {
        fmt.Println(err)
    }
    //文件的关闭
    defer file.Close()
    //文件读取方式一,通过os.Open返回一个文件句柄,然后利用它进行读取
    body,err:=ioutil.ReadAll(file)
    if err !=nil {
        fmt.Println(err)
    }
    fmt.Println(string(body))
}

Method 2: Use the ioutil.ReadFile() method to implement the read operation.

package main

func main(){
    body,err:=ioutil.ReadFile("a.txt")
    if err!=nil {
        fmt.Println(err)
    }
    fmt.Println(string(body))
}

The ReadFile function directly packs the three steps in Mode 1 together. The following is the specific code of the implementation.

func ReadFile(filename string)([]byte,error){
    //打开文件
    f,err:=os.Open(filename)
    if err!=nil {
        return nil,err
    }
    //延迟关闭文件
    defer f.Close()

    //设置读取文件的字节数
    var n int64
    //Stat()方法会返回描述指定文件的信息结构FileInfo
    if fi,err:=f.Stat();err==nil{
        if size:=fi.Size();size<1e9{
            n=size
        }
    }

    //返回读取的文件内容
    return readAll(f,n+bytes.MinRead)
}

FileInfo has the following methods:

Name() string       //返回文件名
Size() int64        //返回文件的字节长度
Mode() FileMode     //文件模式位
ModTime() time.Time //修改时间
IsDir() bool        //是否是目录
Sys()   interface{} //底层数据源

Method 3: Cached read

package main

func main(){
    file,err:=os.Open("a.txt")
    if err!=nil {
        fmt.Println(err)
    }
    defer file.Close()

    //创建一个新的io.Reader,它实现了Read方法
    reader:=bufio.NewReader(file)
    //设置读取的长度
    buf:=make([]byte,1024)
    //读取文件
    _,err=reader.Read(buf)
    if err!=nil {
        fmt.Println(err)
    }
    fmt.Println(string(buf))
}

File writing method 1: Use ioutil.WriteFile()

package main

import (
    "io/ioutil"
)
func main(){
    content:=[]byte("Go is an open source programming language that makes is easy to build simple,reliable,and efficient software)
    err:=ioutil.WriteFile("a.txt",content,0777)
    if err!=nil {
        fmt.Println(err)
    }
    fmt.Println("write file successful")
}

See how WriteFile implements file writing.

func WriteFile(filename string,data []byte,perm os.FileMode) error{
    //打开文件
    f,err:=os.OpenFile(filename,os.O_WRONLY|os.O_CREATE|os.O_TRUNC,perm)
    if err!=nil {
        return err
    }
    //文件的写入
    n,err:=f.Write(data)
    if err==nil && n<len(data){
        err=io.ErrShortWrite
    }
    //关闭文件
    if err1:=f.Close();err==nil{
        err=err1
    }
    return err
}

Method 2: Open the file, and then use Write() to read and write the file. Note: You cannot open it with os.Open() at this time, but with os.OpenFile(). The difference between os.Open() and os.OpenFile()

package main

func main(){
    file,err:=os.OpenFile("a.txt",os.O_RDWR|os.O_CREATE,0777)
    if err!=nil {
        fmt.Println(err)
    }
    defer file.Close()

    content:=[]byte("Go is an open source programing language that makes it easy to build simple,reliable,and efficient software")
    _,err=file.Write(content)
    if err!=nil {
        fmt.Println(err)
    }
    fmt.Println("write file successful")
}

Method 3: Operation through the package provided by bufio with buffer operation If you use the Write method to implement the write operation, you need to use the Flush() method at this time. Analysis of Write method in golang bufio package

package main

func main(){
    file,err:=os.OpenFile("a.txt", os.O_CREATE|os.O_RDWR, 0666)
    if err!=nil {
        fmt.Println(err)
    }
    defer file.Close()

    content:=[]byte("Go is an open source programing language that makes it easy to build simple,reliable,and efficient software")
    //使用NewWriter方法返回的io.Writer缓冲默认大小为4096,也可以使用NewWriterSize方法设置缓存的大小
    newWriter:=bufio.NewWriter(file)
    //将文件写入缓存
    if _,err =newWriter.Write(content);err!=nil {
        fmt.Println(err)
    }
    //从缓存写入到文件中
    if err= newWriter.Flush(); err!=nil {
        fmt.Println(err)
    }
    fmt.Println("write file successful")
}
{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324125436&siteId=291194637