go語言檔案操作

來源:互聯網
上載者:User

標籤:

摘要: 本文主要解說go語言的檔案操作.系統底層的open\write等系統調用,往往操作的檔案對象是檔案描寫敘述符;而C語言庫的檔案操作須要藉助fopen/fread等函數,它們的操作對象是檔案指標.go語言中,對檔案操作進行了進一步封裝……

1.os包中File類

首先,file類是在os包中的,封裝了底層的檔案描寫敘述符和相關資訊,同一時候封裝了Read和Write的實現。

type File struct {    *file}type file struct {    fd  int    name string    dirinfo *dirInfo    nepipe  int}func (f *File) Fd( )uintptr{    if f== nil{        return ^(uintptr(0))    }    return uintptr(f.fd)}

//注意,上文中為什麼能夠用f.fd這個文法,f是File,而File中沒有成員?

func (f *File) Close() error{}func (f *File)Stat ()(fi FileInfo, err error){}

同一時候File類還實現了例如以下方法:

func (f *File) read(b []byte) (n int, err error);func (f *File) write(b []byte) (n int, err error) ;func (f *File) seek(offset int64, whence int) (ret int64, err error) ;
2.io.ReadCloser

在go語言中,帶有er尾碼的往往是介面,ReadCloser顧名思義,就是包括Read和Close方法的借口。我們去看看這兩個介面的定義和實現:

type Reader interface {    Read(p []byte) (n int, err error)}type Closer interface {    Close() error}

注意:不同的包中對Reader的定義是不同的,以下是bufio中對Reader的定義

3. bufio package
type Reader struct {    // contains filtered or unexported fields}type Reader struct {            buf          []byte            rd           io.Reader            r, w         int            err          error            lastByte     int            lastRuneSize int}

bufio是帶有緩衝的io讀寫包,我們先來看一個範例:

    package main    import (        "fmt"        "os"        "bufio"        "io"    )    func main() {        f, err := os.Open("c:\\aaa.txt")//開啟檔案        defer f.Close() //開啟檔案出錯處理        if nil == err {            buff := bufio.NewReader(f) //讀入緩衝            for {                line, err := buff.ReadString(‘\n‘) //以‘\n‘為結束符讀入一行                if err != nil || io.EOF == err {                    break                }                fmt.Print(line)  //能夠對一行進行處理            }        }    }

func NewReader(rd io.Reader) *Reader
//NewReader returns a new Reader whose buffer has the default size.

4.執行個體
type Request struct {    // The message body.    ...    Body io.ReadCloser    ...}

所以說,假設我們想實現Request中的Body,只須要實現io package中的兩個interface就能夠了.

go語言檔案操作

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.