當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang io.SectionReader.ReadAt()用法及代碼示例

在Go語言中,io軟件包為I /O原語提供基本接口。它的主要工作是封裝此類原始之王的正在進行的實現。 Go語言中的SectionReader.ReadAt()函數用於返回NewSectionReader方法讀取的字節數。此方法保留一個緩衝區並以offsets作為其參數。而且,此函數在io包下定義。在這裏,您需要導入“io”包才能使用這些函數。

用法:

func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error)

在這裏,“s”是指向由NewSectionReader方法返回的SectionReader的指針,“p”是指定字節長度的緩衝區,而“off”是int64類型的偏移量,從此位置開始讀取。

返回值:它返回從指定長度的指定緩衝區以及偏移量返回的內容的字節數,並且還返回錯誤(如果有),但如果未發生錯誤,則返回“nil”。

以下示例說明了上述方法的使用:



範例1:

// Golang program to illustrate the usage of 
// io.SectionReader.ReadAt() function 
  
// Including main package 
package main 
  
// Importing fmt, io, and strings 
import ( 
    "fmt"
    "io"
    "strings"
) 
  
// Calling main 
func main() { 
  
    // Defining reader using NewReader method 
    reader:= strings.NewReader("GeeksforGeeks\n") 
  
    // Calling NewSectionReader method with its parameters 
    r:= io.NewSectionReader(reader, 6, 12) 
  
    // Defining buffer using make keyword 
    buf:= make([]byte, 4) 
  
    // Calling ReadAt method with its parameters 
    n, err:= r.ReadAt(buf, 2) 
  
    // If error is not nil then panics 
    if err != nil { 
        panic(err) 
    } 
  
    // Prints output 
    fmt.Printf("Content in buffer:%s\n", buf) 
    fmt.Printf("n:%v\n", n) 
}

輸出:

Content in buffer:Geek
n:4

在上麵的示例中,首先,從NewSectionReader()返回內容,然後從ReadAt()方法中的給定偏移讀取該內容,直到緩衝區中聲明的字節數為止。然後,返回結果內容的字節數作為此處的輸出。此外,上麵緩衝區的內容隻有4個字節,因此,返回“4”,並且在讀取陳述的內容時沒有拋出錯誤,因此錯誤是“nil”。

範例2:

// Golang program to illustrate the usage of 
// io.SectionReader.ReadAt() function 
  
// Including main package 
package main 
  
// Importing fmt, io, and strings 
import ( 
    "fmt"
    "io"
    "strings"
) 
  
// Calling main 
func main() { 
  
    // Defining reader using NewReader method 
    reader:= strings.NewReader("Computer Science!") 
  
    // Calling NewSectionReader method with its parameters 
    r:= io.NewSectionReader(reader, 6, 12) 
  
    // Defining buffer using make keyword 
    buf:= make([]byte, 10) 
  
    // Calling ReadAt method with its parameters 
    n, err:= r.ReadAt(buf, 2) 
  
    // If error is not nil then panics 
    if err != nil { 
        panic(err) 
    } 
  
    // Prints output 
    fmt.Printf("Content in buffer:%s\n", buf) 
    fmt.Printf("n:%v\n", n) 
}

輸出:

panic:EOF

goroutine 1 [running]:
main.main()
    /tmp/sandbox798260752/prog.go:31 +0x263

此處,以上代碼中使用的緩衝區中的內容的字節數少於說明的字節數,因此將引發EOF錯誤。




相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 io.SectionReader.ReadAt() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。