os.Open()-->return value *File, err ***** can be opened after opening
File.Read([]byte)-->count,err, read data, after reading err will display EOF to prove that the entire file is read,
Don't forget to close the file after opening it
You can use defer to delay the final shutdown
derer File.close closes the file
package main import ( "os" "fmt" "io" ) func main() { file,err:= os.Open("C:\\liu\\pro\\aa.txt") if err!=nil{ fmt.Println( "Failed to open the file.." ) return } defer file.Close() //Read data bs := make ([] byte , 4 ) count := 0 //The number of each read for { count, err = file.Read(bs) if err ==io.EOF{ fmt.Println() fmt.Println( "Data read complete.." ) break } fmt.Print(string(bs[:count])) } /* //For the first read, read the corresponding file through file, read the data into bs, the return value is the actual number count read this time, err = file.Read(bs) fmt.Println( err) //<nil> fmt.Println(count) //4 fmt.Println(bs) //[97 98 99 100] fmt.Println(string(bs)) //abcd //The second read count ,err = file.Read(bs) fmt.Println(err) //<nil> fmt.Println(count) //4 fmt.Println(bs) //[101 102 103 104] fmt.Println(string(bs )) //efgh //The third read, read 2 counts, err = file.Read(bs) fmt.Println(err) //<nil> fmt.Println(count) //2 fmt.Println( bs) //[101 102 103 104] //fmt.Println(string(bs)) //efgh ijgh fmt.Println(string(bs[:count])) //ij //For the fourth read, when the end of the file is read, the error returned is io.EOF, and the value of count is 0 count, err= file.Read(bs) fmt.Println(err) //EOF fmt. Println(count) //0 }
File.ReadAt([] byte, off)-->coutn,err, read from the specified off position
package main import ( "os" "fmt" ) func main () { /* Read([]bs), read from the beginning by default, the cursor is at the end, read again, the return error is io.EOF ReadAt([] bs, offset int), read from the specified position * / file , _:=os.Open( "C:\\liu\\pro\\aa.txt" ) bs := make([] byte ,4) /* 1.ReadAt(bs, 0)-->4 2.ReadAt(bs,4)-->4 3.ReadAt(bs,8)-->2 EOF */ count, err:=file.ReadAt(bs,2) fmt.Println(err) //<nil> fmt.Println(count) //4 fmt.Println(string(bs[0:count])) count, err = file.ReadAt(bs,7) fmt.Println(err) //EOF fmt.Println(count) //3 fmt.Println(string(bs[:count])) }