go language file operations

Original link: https://www.cnblogs.com/suoning/p/7225096.html

File Read

os.File package file related operations

  os.File Pkg Doc

 

Read and write parameters

File Open Mode:

const ( 
    O_RDONLY int = syscall.O_RDONLY // read-only mode to open the file 
    O_WRONLY int = syscall.O_WRONLY // Open the file write-only mode 
    O_RDWR int = syscall.O_RDWR // Open the file read-write mode 
    O_APPEND int = syscall.O_APPEND // write when operating the additional data to the end of the file 
    O_CREATE int = syscall.O_CREAT // If there is no will create a new file 
    O_EXCL int = syscall.O_EXCL // and O_CREATE with the use of the file must not exist 
    O_SYNC int = syscall.O_SYNC // open file for synchronizing the I / O 
    O_TRUNC // int = syscall.O_TRUNC If possible, the file open empty 
)

Access Control:

r ——> 004
w ——> 002
x ——> 001

 

Read chestnuts

os.Open || os.OpenFile
package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    // file, err := os.Open("/tmp/test")
    file, err := os.OpenFile("/tmp/test", os.O_CREATE|os.O_WRONLY, 0666)
    if err != nil {
        fmt.Println("Open file error: ", err)
        return
    }
    defer file.Close()    //关闭文件

    reader := bufio.NewReader(file)    //带缓冲区的读写
    for {
        str, err := reader.ReadString('\n')    // 循环读取一行
        if err != nil {
            fmt.Println("read string failed, err: ", err)
            return
        }
        fmt.Println("read string is %s: ", str)
    }
}

 

readline

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
)

func main() {
    file, err := os.Open("C:/test.log")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer file.Close()
    reader := bufio.NewReader(file)
    var line []byte
    for {
        data, prefix, err := reader.ReadLine()
        if err == io.EOF {
            break
        }

        line = append(line, data...)
        if !prefix {
            fmt.Printf("data:%s\n", string(line))
            line = line[:]
        }

    }
}

 

Reads the entire file chestnuts

"Io / ioutil" package implements a function to read the entire document

package main

import (
    "fmt"
    "os"
    "io/ioutil"
)

func main() {
    fileName := "/tmp/test"

    file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)
    if err != nil {
        fmt.Println("Open file error: ", err)
        return
    }
    defer file.Close()

    buf, err := ioutil.ReadAll(file)
    //buf, err := ioutil.ReadFile(fileName)
    if err != nil {
        fmt.Fprintf(os.Stderr, "File Error: %s\n", err)
        return
    }
    fmt.Printf("%s\n", string(buf))
}

 

Read compressed files chestnuts

"Compress / *" package implements a compressed file function.

"Compress / gzip" package implements the gzip compressed file format to read and write 

package main

import (
    "bufio"
    "compress/gzip"
    "fmt"
    "os"
)

func main() {
    fileName := "/tmp/test.log.gz"

    var r *bufio.Reader

    fi, err := os.Open(fileName)
    if err != nil {
        fmt.Println("error", err)
        os.Exit(1)
    }

    fz, err := gzip.NewReader(fi)
    if err != nil {
        fmt.Println("error", err)
        return
    }

    r = bufio.NewReader(fz)
    for {
        line, err := r.ReadString('\n')
        if err != nil {
            fmt.Println("Done reading file")
            return
        }
        fmt.Println(line)
    }
}

 

File Write

file.WriteString || file.Write

package main

import (
    "fmt"
    "os"
)

func main() {
    fileName := "/tmp/test_write"

    file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY, 0755)
    if err != nil {
        fmt.Println("error", err)
        os.Exit(1)
    }
    defer file.Close()

    fileString := "Today very happy."
    file.Seek(0, 2)    // 最后增加
    file.WriteString(fileString)
    //file.Write([]byte(fileString))
}

 

bufio.Writer.WriteString

Buffered write data buffer written in the last To io.Writer interfaces (the Flush method) lower

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    fileName := "/tmp/test_write"

    file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY, 0755)
    if err != nil {
        fmt.Println("error", err)
        os.Exit(1)
    }
    defer file.Close()

    fileWrite := bufio.NewWriter(file)
    fileString := "good.\n"
    for i := 0; i < 10; i++ {
        fileWrite.WriteString(fileString)
    }
    fileWrite.Flush()
}

 

Copy files chestnuts

Copied from one file to another

package main

import (
    "fmt"
    "io"
    "os"
)

func CopyFile(dstName, srcName string) (writeen int64, err error) {
    src, err := os.Open(dstName)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer src.Close()

    dst, err := os.OpenFile(srcName, os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer dst.Close()

    return io.Copy(dst, src)
}

func main() {
    CopyFile("/tmp/test", "/tmp/test_copy1")
    fmt.Println("copy done.")
}

 

chestnut

Whether a file or folder exists

PathExists FUNC (String path) (BOOL, error) { 
    / * 
    determine the file or folder exists 
    an error if the returned to nil, documentation or folder exists 
    an error is returned if the type used os.IsNotExist () judgment is true, described file folder does not exist or 
    if an error is returned to any other type, whether or not in the presence of uncertain 
    * / 
    _, ERR: = os.stat (path) 
    IF ERR == nil { 
        return to true, nil 
    } 
    IF os.IsNotExist (ERR ) { 
        return to false, nil 
    } 
    return to false, ERR 
}

Guess you like

Origin www.cnblogs.com/skzxc/p/11986421.html