Glang file read/write

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

goThe relevant operation function of the file is os under the package, you can view the official documentation of the OS package to learn.

Create a file and write content

There are two functions needed to create a file and write:

 func Create(name string) (*File, error) func (f *File) Write(b []byte) (n int, err error)

The specific code is as follows:

package mainimport (    "log"    "os")func main() {    file, createErr := os.Create("/Users/deweixu/demo.txt")    if createErr != nil {        log.Fatal(createErr)    }    _, writeErr := file.Write([]byte("创建一个文件,并写入内容。"))    if writeErr != nil {        log.Fatal(writeErr)    }    closeErr := file.Close()    if closeErr != nil {        log.Fatal(closeErr)    }}

$ go run create_write.goYou will see that the file was created demo.txt and the content is written.

Read File contents

package mainimport (    "fmt"    "log"    "os")func main() {    //打开文件    file, err := os.Open("/Users/deweixu/demo.txt")    if err != nil {        log.Fatal(err)    }    //创建一个缓冲区, 每次读取1024 byte    buf := make([]byte, 1024)    for {        len, readErr := file.Read(buf)        if len == 0 {            break        }        if readErr != nil {            log.Fatal(err)        }        fmt.Printf("%s", string(buf))    }    fmt.Print("\n")}

$ go run read.goYou can see the read success.

osunder the package there are also operating functions and other functions related to the directory, which can be consulted to learn the relevant documentation.

Copying files

package mainimport (    "log"    "os")func main() {    //创建一个新文件    dstFile, createErr := os.Create("/Users/deweixu/demo-cp.txt")    if createErr != nil {        log.Fatal(createErr)    }    //打开源文件    srcFile, openErr := os.Open("/Users/deweixu/demo.txt")    if openErr != nil {        log.Fatal(openErr)    }    //创建一个缓冲区, 每次读取1024 byte    buf := make([]byte, 1024)    for {        len, readErr := srcFile.Read(buf)        if len == 0 {            break        }        if readErr != nil {            log.Fatal(readErr)        }        _, writeErr := dstFile.Write(buf)        if writeErr != nil {            log.Fatal(writeErr)        }    }    //忽略Close 错误    dstFile.Close()    srcFile.Close()}

go run cp.goComplete the replication.

Because of the File implementation Writer and Reader interface, it can be called io and io/ioutil some functions under the package to manipulate the file, such as the above replication function can be used io under the package of these functions to implement

func Copy(dst Writer, src Reader) (written int64, err error)func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error)func CopyN(dst Writer, src Reader, n int64) (written int64, err error)

The specific code is as follows:

package mainimport (    "io"    "log"    "os")func main() {    //创建一个新文件    dstFile, createErr := os.Create("/Users/deweixu/demo-cp.txt")    if createErr != nil {        log.Fatal(createErr)    }    //打开源文件    srcFile, openErr := os.Open("/Users/deweixu/demo.txt")    if openErr != nil {        log.Fatal(openErr)    }    //创建一个缓冲区, 每次读取1024 byte    buf := make([]byte, 1024)    _, cpErr := io.CopyBuffer(dstFile, srcFile, buf)    if cpErr != nil {        log.Fatal(cpErr)    }    //忽略Close 错误    dstFile.Close()    srcFile.Close()}

Distinguish whether a File directory or a file is open

osThere are also functions on directory operations under the package, which can be consulted on the document, and it is necessary to use functions to differentiate the functions of files and directories stat .

package mainimport (    "fmt"    "log"    "os")func main() {    file, err := os.Open("/Users/deweixu")    if err != nil {        log.Fatal(err)    }    fileInfo, statErr := file.Stat()    if statErr != nil {        log.Fatal(statErr)    }    isDir := fileInfo.IsDir()    fmt.Printf("%t\n", isDir)}
Related Article

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.