In-depth study of Golang file operations

Source: Internet
Author: User

Detailed differences on several methods of reading files

Generally, there are four kinds of common

    1. Using the Read method with the file itself
    2. Using the Read method of the Bufio library
    3. ReadAll () using the Io/ioutil library
    4. ReadFile () using the Io/ioutil library

First, the conclusion.

Bufio is recommended when the size of the block is less than 4KB each time it is read. Newreader (f), greater than 4KB with Bufio.newreadersize (f, Cache size)

To read reader, the diagram is easy to use Ioutil. ReadAll ()

Read files once, using Ioutil. ReadFile ()

It is not recommended to use normal read anyway.

In short, performance is Bufio, convenient on ioutil

HTTPS://SEGMENTFAULT.COM/A/11 ... This article has in-depth research

Examples of the various methods listed below

OS Package

func read1(path string){      fi,err := os.Open(path)      if err != nil{          panic(err)      }      defer fi.Close()        buf := make([]byte,1024)      for{          n,err := fi.Read(buf)          if err != nil && err != io.EOF{panic(err)}          if 0 ==n {break}          fmt.Println(string(buf[:n]))      }  

Bufio Bag

  func read2(path string){      fi,err := os.Open(path)      if err != nil{panic(err)}      defer fi.Close()      r := bufio.NewReader(fi)          buf := make([]byte,1024)      for{          n,err := r.Read(buf)          if err != nil && err != io.EOF{panic(err)}          if 0 ==n {break}          fmt.Println(string(buf[:n]))      }  }  

Ioutil Bag

func read4(path string){    r,err := ioutil.ReadFile(path)    if err != nil{panic(err)}    fmt.Println(r)}

Or

func read3(path string){    fi,err := os.Open(path)    if err != nil{panic(err)}    defer fi.Close()    _,err = ioutil.ReadAll(fi)}

OS Package verbose usage

Directory processing

    • Func Mkdir (name string, perm FileMode) error

Create a directory named name, the permission setting is perm, for example 0777

    • Func mkdirall (Path string, perm FileMode) error

Create a multilevel subdirectory based on path, such as Astaxie_test1_test2.

    • Func Remove (name string) error

Delete directory named name, error when file or other directory is in directory

    • Func RemoveAll (path string) error

Delete the multilevel subdirectory according to path, and if Path is a single name, all subdirectories under that directory are deleted.

package mainimport (    "fmt"    "os")func main() {    os.Mkdir("astaxie", 0777)    os.MkdirAll("astaxie/test1/test2", 0777)    err := os.Remove("astaxie")    if err != nil {        fmt.Println(err)    }    os.RemoveAll("astaxie")}

File creation

There are two ways to create a new file

    • Func Create (name string) (file *file, err Error)

Creates a new file based on the file name provided, returns a file object with the default permission of 0666, and the returned file object is read-write.

    • Func NewFile (fd uintptr, name string) *file

Creates the corresponding file according to the file descriptor, returns a file object

Open the file by using the following two methods:

    • Func Open (name string) (file *file, err Error)

This method opens a file called name, but is read-only, and the internal implementation actually calls OpenFile.

    • Func OpenFile (name string, flag int, perm uint32) (file *file, err Error)

Open a file named Name, flag is open way, read-only, read-write, etc., Perm is the permission

Write a file

    • Func (file *file) Write (b []byte) (n int, err Error)

Writes a byte type of information to a file

    • Func (file *file) writeat (b []byte, off Int64) (n int, err Error)

Writes a byte-type message at the specified position

    • Func (file *file) writestring (S string) (ret int, err Error)

Writes string information to a file

Read the file

    • Func (file *file) Read (b []byte) (n int, err Error)

Read data to B

    • Func (file *file) readat (b []byte, off Int64) (n int, err Error)

Read data from off to B

package mainimport (    "fmt"    "os")func main() {    userFile := "asatxie.txt"    fl, err := os.Open(userFile)            if err != nil {        fmt.Println(userFile, err)        return    }    defer fl.Close()    buf := make([]byte, 1024)    for {        n, _ := fl.Read(buf)        if 0 == n {            break        }        os.Stdout.Write(buf[:n])    }}

deleting files

    • Func Remove (name string) Error

Call this function to delete a file named name

Ioutil Package Details Usage

Package name "Io/ioutil"

Func ReadAll (R io. Reader) ([]byte, error)

Reads all the data in R and returns

func main() {    s := strings.NewReader("Hello World!")    ra, _ := ioutil.ReadAll(s)    fmt.Printf("%s", ra)}

Func ReadFile (filename string) ([]byte, error)

Read files directly

func main() {    ra, _ := ioutil.ReadFile("file path")    fmt.Printf("%s", ra)}

Func WriteFile (filename string, data []byte, Perm OS. FileMode) Error

WriteFile writing data to file filename

If the file does not exist, the file is created with perm permissions

If the file exists, the OS. FileMode different rules for using different

func main() {    fn := "file path""    s := []byte("Hello World!")    ioutil.WriteFile(fn, s, os.ModeAppend)    rf, _ := ioutil.ReadFile(fn)    fmt.Printf("%s", rf)}

Func ReadDir (DirName string) ([]os. FileInfo, error)

ReadDir Read all directories and files in directory Dirmane (not including subdirectories)

Returns the list of information read to the file and any errors encountered during reading

The list of returned files is sorted

func main() {    rd, err := ioutil.ReadDir("file path")    for _, fi := range rd {        fmt.Println("")        fmt.Println(fi.Name())        fmt.Println(fi.IsDir())        fmt.Println(fi.Size())        fmt.Println(fi.ModTime())        fmt.Println(fi.Mode())    }    fmt.Println("")    fmt.Println(err)}

Bufio Package Details Usage

Https://blog.csdn.net/chenbao ...

Refer to this blog first, have time to study

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.