SoFunction
Updated on 2025-03-05

Organize the basic methods of reading and writing files in Go language programming

Copy(dst Writer, src Reader) (written int64, err error) This function is to copy from one file to another file, and all the way to the EOF of the read file, so no error is returned. The parameters are to write to the target and read the target, and return the number of copies bytes and err information of int64.

Copy the codeThe code is as follows:

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

func main() {
 r, _ := ("")
 w, _ := ("")
 num, err := (w, w)
 if err != nil {
  (err)
 }
(num) //Return to int64 11 The one who opens me is the hello widuu inside


CopyN(dst Writer, src Reader, n int64) (writen int64, err error) You can see that it is the same as above, except that there is an additional limit on the number of reads, and then let's look at the code

Copy the codeThe code is as follows:

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

func main() {
 r, _ := ("")
 w, _ := ("")
 num, err := (w, r, 5)
 if err != nil {
  (err)
 }
 defer ()
 b, _ := ("")
(string(b)) //Output hello
 (num)       //5
}


ReadAtLeast(r Reader, buf []byte, min int) (n int, err error) This function reads data from the reader and puts it into our buf, limiting the minimum number of read bytes. If the data we read is smaller than the minimum reader, for example, if you set the value of min is 8, but the number of bytes of data you read is 5, it will return a ```. If it is greater than, it will return ``. After reading, there will be ``~~, talk more. This Reader can use this as long as we satisfy this interface.

Copy the codeThe code is as follows:

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


*File supports func (f *File) Read(b []byte) (n int, err error)

Copy the codeThe code is as follows:

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

func main() {
 r, _ := ("")
 b := make([]byte, 20)
 defer ()
 var total int
 for {
  n, err := (r, b, 8)
  if err == nil {
   ("Read enough value:", string(b)) // Read enough value: hello widuu
  }
if err == { //The read data is less than the minimum read data we limited 8
   ("Read fewer value:", string(b[0:n]))
  }
  
if err == {   //This is the buf we set, that is, b is less than our limited 8
   ("buf too Short")
   (1)
  }
if err == { //Readed Output
   ("Read end total", total) //Read end total 11
   break
  }
  total = total + n
 }
}


ReadFull(r Reader, buf []byte) (n int, err error) This function is similar to the above function, except that it reads len(buf) and puts it in buf

Copy the codeThe code is as follows:

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

func main() {
 r, _ := ("")
 b := make([]byte, 20)
 num, err := (r, b)
 defer ()
 if err == {
  ("Read end total", num)
 }
 if err == {
("Read fewer value:", string(b[:num])) //Read fewer value: hello widuu, the length of buf is still greater than the length of read
  return
 }

("Read  value:", string(b)) //If b is 5, it will appear here
}


WriteString(w Writer, s string) (n int, err error) has been finished and read, of course, it has to be written. This function mainly writes characters into the write target, returns the number of bytes written and the error error, mainly the permission error, and the writing is in it! All the writer structures can be written

Copy the codeThe code is as follows:

type Writer interface {
    Write(p []byte) (n int, err error)
}
Like read, our *File has func (f *File) Write(b []byte) (n int, err error). Of course, we already have WirteString in our *File func (f *File) WriteString(s string) (ret int, err error)
import (
 "fmt"
 "io"
 "io/ioutil"
 "os"
)

func main() {
 w, _ := ("", os.O_RDWR, )
 n, err := (w, "ni hao ma")
 if err != nil {
(err) //When I use(), there is no permission. Sad ~~Output write: Access is denied.
 }
 defer ()
 b, _ := ("")
 ("write total", n) //write total 9
 (string(b))        // ni hao ma
}


LimitedReader

Copy the codeThe code is as follows:

type LimitedReader struct {
R Reader // Reader
N int64 // Maximum byte limit
}


Only one method is implemented func (l *LimitedReader) Read(p []byte) (n int, err error) In fact, it is not difficult to find that this and our ReadAtLast() are the rhythm of the brothers.

Copy the codeThe code is as follows:

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

func main() {
 reader, _ := ("")
 limitedreader := {
  R: reader,
  N: 20,
 }
 p := make([]byte, 10)
 var total int
 for {
  n, err := (p)
  if err == {
   ("read total", total)     //read total 11
   ("read value", string(p)) //read value hello widuu
   break
  }
  total = total + n

 }

}


PipeReader

Copy the codeThe code is as follows:

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


(1) func Pipe() (*PipeReader, *PipeWriter) creates a pipeline and returns its reader and writer. This will perform pipeline synchronization in memory. Its turn on will then wait for input, without internal buffering. It is safe to call Read and Write to each other and write in parallel.

Copy the codeThe code is as follows:

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

func main() {
 r, w := ()
 ((r)) //*
 ((w)) //*
}


(2) func (r *PipeReader) Close() error After the pipeline is closed, the in progress or subsequent write operation returns ErrClosedPipe
Copy the codeThe code is as follows:

import (
 "fmt"
 "io"
)

func main() {
 r, w := ()
 ()

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

 if err == {
("The pipeline has been closed and cannot be written") //The pipeline has been closed and cannot be written
 }
}


(3) func (r *PipeReader) CloseWithError(err error) error This is when the above is closed, the writer will return the error message

Copy the codeThe code is as follows:

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

func main() {
 r, w := ()
 ()
err := ("Pipe character is closed") // We have already mentioned the errors package before. Just one method that New can't do, you can look at the previous one
 (err)
 _, err = ([]byte("test"))
 if err != nil {
(err) //The pipe character is closed
 }
}


(4)func (r *PipeReader) Read(data []byte) (n int, err error) Standard reading interface, it reads data from the pipeline, blocks until a write interface is closed. If an error occurs on the write end, it will return an error, otherwise the returned EOF

Copy the codeThe code is as follows:

import (
 "fmt"
 "io"
)

func main() {
 r, w := ()
 go ([]byte("hello widuu"))
 d := make([]byte, 11)
n, _ := (d) //Read data from the pipeline
 (string(d))
 (n)
}