溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Go語(yǔ)言中如何對(duì)文件進(jìn)行讀寫操作

發(fā)布時(shí)間:2022-04-14 15:41:55 來(lái)源:億速云 閱讀:379 作者:iii 欄目:編程語(yǔ)言

這篇文章主要介紹“Go語(yǔ)言中如何對(duì)文件進(jìn)行讀寫操作”,在日常操作中,相信很多人在Go語(yǔ)言中如何對(duì)文件進(jìn)行讀寫操作問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”Go語(yǔ)言中如何對(duì)文件進(jìn)行讀寫操作”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!

1.func Copy(dst Writer, src Reader) (written int64, err error)這個(gè)函數(shù)是從一個(gè)文件讀取拷貝到另外一個(gè)文件,一直拷貝到讀取文件的EOF,所以不會(huì)返回io.EOF錯(cuò)誤,參數(shù)是寫入目標(biāo)器和讀取目標(biāo)器,返回int64的拷貝字節(jié)數(shù)和err信息

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

func main() {
 r, _ := os.Open("test.txt")
 w, _ := os.Create("write.txt")
 num, err := io.Copy(w, w)
 if err != nil {
  fmt.Println(err)
 }
 fmt.Println(num) //返回int64的11 打開我的write.txt正是test.txt里邊的hello widuu

2.func CopyN(dst Writer, src Reader, n int64) (written int64, err error)看函數(shù)就知道了跟上述的是一樣的,只是多加了一個(gè)讀取數(shù)的限制,然后我們看下代碼

復(fù)制代碼 代碼如下:


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

func main() {
 r, _ := os.Open("test.txt")
 w, _ := os.Create("write1.txt")
 num, err := io.CopyN(w, r, 5)
 if err != nil {
  fmt.Println(err)
 }
 defer r.Close()
 b, _ := ioutil.ReadFile("write1.txt")
 fmt.Println(string(b)) //輸出 hello
 fmt.Println(num)       //5
}

3.func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error)這個(gè)函數(shù)就是從讀取器中讀取數(shù)據(jù)放到我們的buf中,限定了最小的讀取字節(jié)數(shù),如果我們讀取的數(shù)據(jù)小于最小讀取器,譬如你設(shè)定min的值是8,但是你讀取的數(shù)據(jù)字節(jié)數(shù)是5就會(huì)返回一個(gè)`io.ErrUnexpectedEOF`,如果大于就會(huì)返回`io.ErrShortBuffer`,讀取完畢會(huì)有`io.EOF`~~,多講一些哈,這個(gè)Reader只要我們滿足這個(gè)interface就可以用這個(gè)

復(fù)制代碼 代碼如下:


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


其中*File就支持func (f *File) Read(b []byte) (n int, err error)

復(fù)制代碼 代碼如下:

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

func main() {
 r, _ := os.Open("write1.txt")
 b := make([]byte, 20)
 defer r.Close()
 var total int
 for {
  n, err := io.ReadAtLeast(r, b, 8)
  if err == nil {
   fmt.Println("Read enough value:", string(b)) // Read enough value: hello widuu
  }
  if err == io.ErrUnexpectedEOF { //讀取了的數(shù)據(jù)小于我們限定的最小讀取數(shù)據(jù)8
   fmt.Println("Read fewer value:", string(b[0:n]))
  }
  
  if err == io.ErrShortBuffer{   //這個(gè)是我們?cè)O(shè)定的buf也就是b小于我們限定8
   fmt.Println("buf too Short")
   os.Exit(1)
  }
  if err == io.EOF { //讀完了 輸出
   fmt.Println("Read end total", total) //Read end total 11
   break
  }
  total = total + n
 }
}

4.func ReadFull(r Reader, buf []byte) (n int, err error)這個(gè)函數(shù)和上邊的函數(shù)是相似,只不過(guò)是讀取len(buf)個(gè),放在buf中

復(fù)制代碼 代碼如下:

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

func main() {
 r, _ := os.Open("write.txt")
 b := make([]byte, 20)
 num, err := io.ReadFull(r, b)
 defer r.Close()
 if err == io.EOF {
  fmt.Println("Read end total", num)
 }
 if err == io.ErrUnexpectedEOF {
  fmt.Println("Read fewer value:", string(b[:num])) //Read fewer value: hello widuu,依然是buf長(zhǎng)度大于讀取的長(zhǎng)度
  return
 }

 fmt.Println("Read  value:", string(b)) //如果b是5 就出現(xiàn)這里
}

5.func WriteString(w Writer, s string) (n int, err error)弄完讀了,當(dāng)然帶要寫了,這個(gè)函數(shù)主要是向?qū)懭肽繕?biāo)中寫入字符創(chuàng),返回是寫入的字節(jié)數(shù)還有error錯(cuò)誤,主要是權(quán)限的錯(cuò)誤,其中寫入呀!都是writer這個(gè)結(jié)構(gòu)就可以寫入

復(fù)制代碼 代碼如下:

type Writer interface {
    Write(p []byte) (n int, err error)
}
跟read一樣我們的*File是有func (f *File) Write(b []byte) (n int, err error),當(dāng)然其實(shí)我們的*File中就已經(jīng)有WirteString了func (f *File) WriteString(s string) (ret int, err error)
import (
 "fmt"
 "io"
 "io/ioutil"
 "os"
)

func main() {
 w, _ := os.OpenFile("write1.txt", os.O_RDWR, os.ModePerm)
 n, err := io.WriteString(w, "ni hao ma")
 if err != nil {
  fmt.Println(err) //當(dāng)我用os.open()的時(shí)候木有權(quán)限  悲催的~~輸出write write1.txt: Access is denied.
 }
 defer w.Close()
 b, _ := ioutil.ReadFile("write1.txt")
 fmt.Println("write total", n) //write total 9
 fmt.Println(string(b))        // ni hao ma
}

6.type LimitedReader

復(fù)制代碼 代碼如下:

type LimitedReader struct {
    R Reader // 讀取器了
    N int64  // 最大字節(jié)限制
}


只實(shí)現(xiàn)了一個(gè)方法func (l *LimitedReader) Read(p []byte) (n int, err error)其實(shí)我們不難發(fā)現(xiàn)這個(gè)跟我們的ReadAtLast()就是親兄弟的節(jié)奏

復(fù)制代碼 代碼如下:


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

func main() {
 reader, _ := os.Open("test.txt")
 limitedreader := io.LimitedReader{
  R: reader,
  N: 20,
 }
 p := make([]byte, 10)
 var total int
 for {
  n, err := limitedreader.Read(p)
  if err == io.EOF {
   fmt.Println("read total", total)     //read total 11
   fmt.Println("read value", string(p)) //read value hello widuu
   break
  }
  total = total + n

 }

}

7.type PipeReader

復(fù)制代碼 代碼如下:


type PipeReader struct {
    // contains filtered or unexported fields
}


(1)func Pipe() (*PipeReader, *PipeWriter)創(chuàng)建一個(gè)管道,并返回它的讀取器和寫入器,這個(gè)會(huì)在內(nèi)存中進(jìn)行管道同步,它的開啟會(huì)io.Reader然后等待io.Writer的輸入,沒(méi)有內(nèi)部緩沖,它是安全的調(diào)用Read和Write彼此和并行調(diào)用寫

復(fù)制代碼 代碼如下:

import (
 "fmt"
 "io"
 "reflect"
)

func main() {
 r, w := io.Pipe()
 fmt.Println(reflect.TypeOf(r)) //*io.PipeReader
 fmt.Println(reflect.TypeOf(w)) //*io.PipeWriter
}


(2)func (r *PipeReader) Close() error管道關(guān)閉后,正在進(jìn)行或后續(xù)的寫入Write操作返回ErrClosedPipe

復(fù)制代碼 代碼如下:


import (
 "fmt"
 "io"
)

func main() {
 r, w := io.Pipe()
 r.Close()

 _, err := w.Write([]byte("hello widuu")) 

 if err == io.ErrClosedPipe {
  fmt.Println("管道已經(jīng)關(guān)閉無(wú)法寫入") //管道已經(jīng)關(guān)閉無(wú)法寫入
 }
}


(3)func (r *PipeReader) CloseWithError(err error) error這個(gè)就是上邊的r.Close關(guān)閉的時(shí)候,寫入器會(huì)返回錯(cuò)誤的信息

復(fù)制代碼 代碼如下:

import (
 "errors"
 "fmt"
 "io"
)

func main() {
 r, w := io.Pipe()
 r.Close()
 err := errors.New("管道符關(guān)閉了") //errors這個(gè)包我們前邊已經(jīng)說(shuō)過(guò)了,就一個(gè)方法New不會(huì)的可以看看前邊的
 r.CloseWithError(err)
 _, err = w.Write([]byte("test"))
 if err != nil {
  fmt.Println(err) //管道符關(guān)閉了
 }
}


(4)func (r *PipeReader) Read(data []byte) (n int, err error)標(biāo)準(zhǔn)的閱讀接口,它從管道中讀取數(shù)據(jù)、阻塞一直到一個(gè)寫入接口關(guān)閉,如果寫入端發(fā)生錯(cuò)誤,它就會(huì)返回錯(cuò)誤,否則返回的EOF

復(fù)制代碼 代碼如下:


import (
 "fmt"
 "io"
)

func main() {
 r, w := io.Pipe()
 go w.Write([]byte("hello widuu"))
 d := make([]byte, 11)
 n, _ := r.Read(d) //從管道里讀取數(shù)據(jù)
 fmt.Println(string(d))
 fmt.Println(n)
}

到此,關(guān)于“Go語(yǔ)言中如何對(duì)文件進(jìn)行讀寫操作”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI