golang逐行處理檔案

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

 golang 提供了package bufio。bufio.NewReader()建立一個預設大小的readbuf,當然,也可以bufio.NewReaderSize。

func NewReader(rd io.Reader) *Reader    NewReader returns a new Reader whose buffer has the default size(4096).func NewReaderSize(rd io.Reader, size int) *Reader    NewReaderSize returns a new Reader whose buffer has at least the    specified size. If the argument io.Reader is already a Reader with large    enough size, it returns the underlying Reader.

bufio

func (b *Reader) ReadByte() (c byte, err error)    ReadByte reads and returns a single byte. If no byte is available,    returns an error.func (b *Reader) ReadBytes(delim byte) (line []byte, err error)    ReadBytes reads until the first occurrence of delim in the input,    returning a slice containing the data up to and including the delimiter.    If ReadBytes encounters an error before finding a delimiter, it returns    the data read before the error and the error itself (often io.EOF).    ReadBytes returns err != nil if and only if the returned data does not    end in delim. For simple uses, a Scanner may be more convenient.func (b *Reader) ReadString(delim byte) (line string, err error)    ReadString reads until the first occurrence of delim in the input,    returning a string containing the data up to and including the    delimiter. If ReadString encounters an error before finding a delimiter,    it returns the data read before the error and the error itself (often    io.EOF). ReadString returns err != nil if and only if the returned data    does not end in delim. For simple uses, a Scanner may be more    convenient.

ReadByte這個介面,和C語言中fgetc很接近,每次讀取一個位元組。ReadBytes和ReadString都可以實現逐行讀取,只要delim設定為'\n'.

package mainimport "fmt"import "os"import "io"import "flag"import "bufio"var num_flag = flag.Bool("n",false,"num each line")func usage(){    fmt.Printf("%s %s\n",os.Args[0],"filename")}func cat(r *bufio.Reader){    i := 1    for {        //buf,err := r.ReadBytes('\n')        buf,err := r.ReadString('\n')        if err == io.EOF{            break        }        if *num_flag{            fmt.Fprintf(os.Stdout,"%5d %s",                        i,buf)            i++        }else{            fmt.Fprintf(os.Stdout,"%s",buf)        }    }    return }func main(){    flag.Parse()    if(flag.NArg() == 0){        cat(bufio.NewReader(os.Stdin))    }    for i:=0;i<flag.NArg();i++{        f,err := os.OpenFile(flag.Arg(i),os.O_RDONLY,0660)        if err != nil{            fmt.Fprintf(os.Stderr,"%s err read from %s : %s\n",            os.Args[0],flag.Arg(0),err)            continue        }        cat(bufio.NewReader(f))        f.Close()    }}

用scaner逐行讀取

func cat(scanner *bufio.Scanner) error{    for scanner.Scan(){        fmt.Println(scanner.Text())          //fmt.Fprintf(os.Stdout,"%s\n",scanner.Text())    }    return scanner.Err()}

注意,為啥執行Scan,Text()函數就能返回下一行呢?因為預設的分割函數就是ScanLines.如你有特殊的需求來分割,func (s *Scanner) Split(split SplitFunc)

這個函數可以制定SplitFunc。你可以定製自己的分割函數。

    需要注意的是,Scan會將分割符號\n去除,如果Fprintf輸出的話,不添加\n列印,會出現沒有換行的現象,如下所示

fmt.Fprintf(os.Stdout,"%s",scanner.Text())
manu@manu-hacks:~/code/go/self$ go run mycat_v2.go test.txt this is test file created by goif not existed ,please create this fileif existed, Please write appendhello world,hello gothis is test file created by goif not existed ,please create this fileif existed, Please write appendhello world,hello gomanu@manu-hacks:~/code/go/self$ cat test.txt this is test file created by goif not existed ,please create this fileif existed, Please write appendhello world,hello gothis is test file created by goif not existed ,please create this fileif existed, Please write appendhello world,hello go

  調用部分的代碼如下:

 f,err := os.OpenFile(flag.Arg(i),os.O_RDONLY,0660)                 ...        error := cat(bufio.NewScanner(f))        if err != nil{            fmt.Fprintf(os.Stderr,"%s err read from %s : %s\n",            os.Args[0],flag.Arg(i),error)        }


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.