Go語言程式:統計檔案中的行數


在 Go 程式語言中,檔案是用於儲存資料的命名資源,可以從中讀取或寫入資料。它為程式提供了一種持久化資料的方法,即使程式執行完畢後資料仍然存在。本文將討論幾種統計檔案行數的方法。

方法 1:使用使用者自定義函式

在本方法中,我們將編寫一個 Go 語言程式,使用 bufio、fmt 和 os 包來統計檔案中存在的行數。

演算法

  • 步驟 1 − 首先,我們需要匯入 fmt、bufio 和 os 包。

  • 步驟 2 − 現在,開始 main 函式。在 main() 函式內部建立一個新檔案並將其儲存在一個變數中。

  • 步驟 3 − 如果在此過程中發生任何錯誤,則將其儲存在名為 err 的變數中並在螢幕上打印出來。

  • 步驟 4 − 現在,為了寫入此檔案,請使用 bufio 包中的 NewWriter() 函式,並使用另一個函式 WriteString() 將字串值輸入到檔案中。

  • 步驟 5 − 現在,使用 Open() 函式開啟檔案,並使用 scan() 函式讀取檔案中存在的資料。

  • 步驟 6 − 再次使用 for 迴圈迭代檔案中存在的資料,並在每次獲取新行時遞增 count 變數。

  • 步驟 7 − 迭代完成後,count 變數包含該特定檔案中存在的行數。

  • 步驟 8 − 最後,我們需要使用 fmt.Println() 函式在螢幕上列印此結果。

示例 1

在以下示例中,我們將使用使用者自定義函式來統計檔案中存在的行數。

package main
import (
   "bufio"
   "fmt"
   "os"
)

func main() {
   // creating a new file
   file, err := os.Create("newFile.txt")
   if err != nil {
      fmt.Println(err)
      return
   }
   defer file.Close()

   // writing data in the file
   writer := bufio.NewWriter(file)
   _, err = writer.WriteString("Hello, World!\n this is the first line\n followed by the second line\n and the third one")
   if err != nil {
      fmt.Println(err)
      return
   }
   err = writer.Flush()
   if err != nil {
      fmt.Println(err)
      return
   }

   // fetching the file
   file, err = os.Open("newFile.txt")
   if err != nil {
      fmt.Println(err)
      return
   }
   defer file.Close()

   scanner := bufio.NewScanner(file)
   scanner.Split(bufio.ScanLines)

   // getting the number of lines
   var count int
   for scanner.Scan() {
      count++
   }
   if err := scanner.Err(); err != nil {
      fmt.Println(err)
      return
   }
   fmt.Println("Number of lines in file:", count)
}

輸出

Number of lines in file: 4

方法 2:使用內建函式

在本方法中,我們將編寫一個 Go 語言程式,使用內建庫函式來統計檔案中存在的行數。

語法

func len(v Type) int

len() 函式用於獲取任何引數的長度。它將要查詢其長度的資料型別變數作為引數,並返回表示變數長度的整數值。

func Split(str, sep string) []string

Split() 函式用於透過提供的分隔符分割字串。此函式存在於 strings 包中,它接受要分割的字串以及分隔符作為引數。然後,該函式返回最終的字串陣列作為結果。

演算法

  • 步驟 1 − 首先,我們需要匯入所需的包。

  • 步驟 2 − 現在,開始 main 函式。在 main() 函式內部建立一個新檔案並將其儲存在一個變數中。

  • 步驟 3 − 現在,為了寫入此檔案,請使用函式 WriteString() 並將字串值輸入到檔案中。

  • 步驟 4 − 現在,使用 ioutil 包中的 ReadFile() 函式開啟檔案以讀取檔案中存在的資料。

  • 步驟 5 − 使用 split() 函式統計行數並在螢幕上打印出來。

示例 1

在本例中,我們將學習如何使用諸如 writestring() 之類的內建函式來統計檔案中存在的行數。

package main
import (
   "bufio"
   "fmt"
   "io/ioutil"
   "os"
   "strings"
)

func main() {
   // creating a new file
   file, err := os.Create("newFile.txt")
   if err != nil {
      fmt.Println(err)
      return
   }
   defer file.Close()

   // writing data in the file
   writer := bufio.NewWriter(file)
   _, err = writer.WriteString("Hello, World!\n this is the first line\n followed by the second line\n and the third one\n and a new one")
   if err != nil {
      fmt.Println(err)
      return
   }
   err = writer.Flush()
   if err != nil {
      fmt.Println(err)
      return
   }

   // fetching the file
   data, err := ioutil.ReadFile("newFile.txt")
   if err != nil {
      panic(err)
   }
   lines := strings.Split(string(data), "\n")
   fmt.Printf("Number of lines: %d\n", len(lines))
}

輸出

Number of lines: 5

示例 2

在本例中,我們使用了 reader 包中存在的內建庫函式 ReadLine(),以便編寫一個 Go 語言程式來統計給定檔案中的行數。

package main
import (
   "bufio"
   "fmt"
   "os"
)

func main() {
   // creating a new file
   file, err := os.Create("newFile.txt")
   if err != nil {
      fmt.Println(err)
      return
   }
   defer file.Close()

   // writing data in the file
   writer := bufio.NewWriter(file)
   _, err = writer.WriteString("Hello, World!\n this is the first line\n followed by the second line\n and the third one\n and a new one")
   if err != nil {
      fmt.Println(err)
      return
   }
   err = writer.Flush()
   if err != nil {
      fmt.Println(err)
      return
   }
   file, err = os.Open("newFile.txt")
   if err != nil {
      panic(err)
   }
   defer file.Close()

   reader := bufio.NewReader(file)
   lineCount := 0
   for {
      _, _, err := reader.ReadLine()
      if err != nil {
         break
      }
      lineCount++
   }
   fmt.Printf("Number of lines: %d\n", lineCount)
}

輸出

Number of lines: 5

結論

在第一個示例中,我們使用了使用者自定義函式,而在第二個方法中,我們使用了兩個內建函式示例來統計檔案中存在的行數。

更新於: 2023年2月22日

2K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

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