Go語言程式:從現有檔案中讀取指定數量的字元


在Go語言中,我們可以使用`ioutil.ReadFile()`讀取檔案,並使用for迴圈計時器來限制讀取的字元數,同時使用`os.Open`和`bufio.NewReader`函式分別執行檔案操作和讀取操作。本文將學習如何使用Go語言的`os`和`bufio`包從現有檔案中讀取指定數量的字元。

語法

ioutil.ReadFile(file)

`ReadFile()`函式位於`ioutil`包中,用於讀取給定檔案。該函式接受要讀取的檔案作為引數。要從檔案中讀取指定數量的字元,我們可以使用`ReadFile`函式,然後從返回的位元組切片中提取所需的字元數量。

File.Read(file name)

`Read`方法返回兩個值:實際讀取的字元數 (n) 和錯誤 (err)。我們檢查是否存在錯誤,如果存在,則檢查錯誤是否為EOF(檔案結尾)錯誤。如果不是EOF錯誤,則列印錯誤訊息並返回。

bufio.NewReader()

此函式屬於Go的`bufio`包。此函式的主要目標是以較大的塊而不是逐行讀取資料並存儲在緩衝區中。`io.reader`和緩衝區大小作為引數傳遞給此函式。

os.Open()

此函式是`os`包的一部分。它用於開啟檔案以進行讀取。它接受一個輸入,即要開啟的檔名。

方法一

在這種方法中,我們將使用`ioutil`包中提供的`Read()`函式從現有檔案中讀取字元。

演算法

  • 首先,我們需要匯入`fmt`和`ioutil`包。

  • 現在,啟動`main()`函式。在`main()`函式內部,使用`ReadFile()`函式讀取檔案的內容。

  • 檢查讀取檔案時是否存在任何錯誤。如果發生錯誤,則在螢幕上列印錯誤訊息。

  • 如果沒有生成錯誤,則在螢幕上列印檔案的內容。

  • 使用`fmt.Println`函式將切片後的位元組切片列印為字串。

示例

在下面的示例中,我們將建立一個Go語言程式,使用`ioutil`包從現有檔案中讀取指定數量的字元。

package main

import (
   "fmt"
   "io/ioutil"
)

func main() {
   content, err := ioutil.ReadFile("file.txt")
   if err != nil {
      fmt.Println("Error reading file:", err)
      return
   }

   if len(content) < 5 {
      fmt.Println("File is too small to read 5 characters")
      return
   }

   characters := content[:]
   fmt.Println("The contents of given file are:\n", string(characters))
}

輸出

History of Computers
It is very difficult to find the exact origin of computers.
But according to some experts computer exists at the time of world war-II.
Also, at that time they were used for keeping data. But, it was for only government use and not for public use.
Above all, in the beginning, the computer was a very large and heavy machine.

方法二

在這種方法中,我們將編寫一個Go語言程式,使用`bufio`包中提供的`Read()`函式從檔案中讀取指定的字元。要使用`bufio`包從檔案中讀取指定數量的字元,我們可以使用`NewReader`函式建立一個新的緩衝區讀取器,然後使用`Read`方法讀取所需數量的字元。

演算法

  • 首先,我們需要匯入“os”、“fmt”和“bufio”包。

  • 現在,呼叫`main()`函式。在`main()`函式內部,呼叫`Open()`函式開啟檔案,並呼叫`bufio.NewReader`函式為檔案建立一個新的讀取器。

  • 使用讀取器的`Read`方法將指定數量的字元讀取到位元組切片中。

  • 檢查讀取檔案時是否發生錯誤。如果發生錯誤,則在螢幕上列印錯誤訊息。

  • 如果沒有發生錯誤,則使用`fmt.Println`函式將位元組切片列印為字串。

示例

在這個示例中,我們將學習如何使用Go語言的`os`和`bufio`包從現有檔案中讀取指定數量的字元。

package main

import (
   "bufio"
   "fmt"
   "os"
)

func main() {
   file, err := os.Open("file.txt")
   if err != nil {
      fmt.Println("Error opening file:", err)
      return
   }
   defer file.Close()

   reader := bufio.NewReader(file)
   characters := make([]byte, 400)
   n, err := reader.Read(characters)
   if err != nil {
      fmt.Println("Error reading file:", err)
      return
   }

   if n < 5 {
      fmt.Println("File is too small to read 5 characters")
      return
   }
   fmt.Println(string(characters))
}

輸出

The history of programming languages spans from documentation of early mechanical computers to modern
tools for software development. Early programming languages were highly specialized, relying on
mathematical notation and similarly obscure Syntax. Throughout the 20th century, research in compiler
theory led to the creation of high-level programming languages.

方法三

在這種方法中,我們將編寫一個Go語言程式,使用`io`包中提供的各種函式從現有檔案中讀取指定數量的字元。

演算法

  • 首先,我們需要匯入“fmt”、“io”和“os”包。

  • 然後,啟動`main()`函式。在`main()`函式內部,使用`os.Open`函式開啟檔案。

  • 檢查開啟檔案時是否發生錯誤。如果發生錯誤,則列印錯誤訊息並返回。

  • 如果沒有發生錯誤,則使用檔案的`Read`方法將指定數量的字元讀取到位元組切片中。

  • 檢查讀取檔案時是否發生錯誤。

  • 如果發生錯誤,則列印錯誤訊息並返回。如果沒有發生錯誤,則檢查實際讀取的字元數是否小於所需的字元數。

  • 如果是,則列印一條訊息,說明檔案太小,無法讀取所需的字元數。

  • 如果實際讀取的字元數等於或大於所需的字元數,則使用`fmt.Println`函式將位元組切片列印為字串。

示例

在這個示例中,我們將學習如何建立一個Go語言程式,使用`io`和`os`包從現有檔案中讀取指定數量的字元。

package main

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

func main() {
   file, err := os.Open("file.txt")
   if err != nil {
      fmt.Println("Error opening file:", err)
      return
   }
   defer file.Close()

   characters := make([]byte, 450)
   n, err := file.Read(characters)
   if err != nil && err != io.EOF {
      fmt.Println("Error reading file:", err)
      return
   }

   if n < 5 {
      fmt.Println("File is too small to read 5 characters")
      return
   }

   fmt.Println(string(characters))
}

輸出

Modern humans (Homo sapiens), the species? that we are, means ‘wise man’ in Latin. Our species is the only surviving species of the genus
Homo but where we came from has been a topic of much debate. Modern humans originated in Africa within the past 200,000 years
and evolved from their most likely recent common ancestor, Homo erectus, which means ‘upright man’ in Latin.
Homo erectus is an extinct species of human that lived between 1.9 million and 135,000 years ago.

結論

我們已經成功地編譯並執行了一個Go語言程式,該程式可以從現有檔案中讀取指定數量的字元,並附帶示例。這裡我們使用了三個示例。第一個示例使用了`ioutil`包,它提供了一個易於使用的檔案讀取函式,而`bufio`和`io`包提供了更靈活、更高效的檔案讀取方法,分別用於第二個和第三個示例。在第三個示例中,我們使用了`os`包。

更新於:2023年5月3日

瀏覽量:508

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.