Go語言程式寫入檔案


在 Go 程式語言中,我們可以使用 os.Create 和 ioutil.WriteFile 來寫入檔案。在 Go 中,作業系統可以用來表示檔案。os 包中的檔案型別提供了開啟、讀取、寫入和操作檔案的方法。

方法 1:使用 os.Create 函式

在這個程式中,我們使用 os.Create 來建立一個新檔案,或者如果檔案已存在,則開啟它。使用 WriteString 函式寫入字串時,檔案會被延遲關閉。Close 確保在應用程式結束時正確關閉檔案。

語法

Os.Create 

在 Go 程式語言中,create 是 os 包的一部分,此函式建立一個新檔案,它包含一個引數,即要建立的檔名。

演算法

  • 步驟 1 − 建立一個 package main 並宣告 fmt(格式化包)和 os 包,其中 main 生成可執行程式碼,fmt 幫助格式化輸入和輸出。

  • 步驟 2 − 在 main 中使用 os.Create 開啟檔案以進行寫入。

  • 步驟 3 − 檢查任何潛在的檔案建立問題,例如檔案未找到。

  • 步驟 4 − 所有操作完成後,使用 defer 關鍵字關閉檔案。

  • 步驟 5 − 使用檔案將字串寫入檔案,使用 WriteString 方法。

  • 步驟 6 − 檢查您的文字是否存在任何錯誤,例如許可權不足。

示例

在這個示例中,我們將使用 os.Create 函式寫入檔案。讓我們看看程式碼是如何執行的。

package main
import (
   "fmt"
   "os"
)
//create main function to execute the program
func main() {
   // Open the file for writing
   file, errs := os.Create("myfile.txt")
   if errs != nil {
      fmt.Println("Failed to create file:", errs)
      return
   }
   defer file.Close()

   // Write the string "Hello, World!" to the file
   _, errs = file.WriteString("Hello, World!")
   if errs != nil {
      fmt.Println("Failed to write to file:", errs) //print the failed message
      return
   }
   fmt.Println("Wrote to file 'myfile.txt'.") //print the success message
}

輸出

Wrote to file 'myfile.txt'.

方法 2:使用 ioutil.WriteFile

在這個程式中,我們使用 ioutil.WriteFile 函式將字串寫入檔案。檔名是第一個引數,要寫入的資料作為位元組切片是第二個引數,檔案許可權是第三個引數。如果出現問題,函式會返回一個錯誤,我們在程式中檢查該錯誤。

語法

ioutil.WriteFile

在 Go 中,WriteFile 屬於 ioutil 包,包含三個引數,第一個是要寫入資料的檔名,第二個是要寫入的資料,第三個是檔案許可權。如果函式執行成功,資料將寫入檔案。

演算法

  • 步驟 1 − 建立一個 package main 並宣告 fmt(格式化包)和 io/ioutil 包,其中 main 生成可執行程式碼,fmt 幫助格式化輸入和輸出。

  • 步驟 2 − 使用 main 函式中的 ioutil.WriteFile 將字串寫入檔案。

  • 步驟 3 − 檔名是第一個引數,要寫入的資料(作為位元組切片)是第二個引數。這裡,第三個引數是檔案許可權。

  • 步驟 4 − 檢查您的文字是否存在任何錯誤,例如許可權不足。

  • 步驟 5 − 如果沒有問題,則列印一條訊息,說明檔案已成功寫入。

  • 步驟 6 − 使用 fmt.Println() 函式執行列印語句。

示例

在這個示例中,我們將使用 ioutil.WriteFile 方法寫入檔案。讓我們透過程式碼看看它是如何執行的。

package main
import (
   "fmt"
   "io/ioutil"
)

//create main function to execute the program
func main() {
   // Write the string to the file
   err := ioutil.WriteFile("myfile.txt", []byte("Hello, alexa!"), 0644)
   if err != nil {
      fmt.Println("Failed to write to file:", err)  //print the failed message
      return
   }
   fmt.Println("Wrote to the file 'myfile.txt'.")  //print the success message
}

輸出

Wrote to the file 'myfile.txt'.

結論

我們使用兩種方法執行了寫入檔案的程式。在第一種方法中,我們使用了 os.Create 函式,在第二個示例中,我們使用了 ioutil.WriteFile 命令來執行程式。如果內容成功寫入檔案,則會列印成功訊息,但如果無法寫入檔案,則會在控制檯上列印失敗訊息。

更新於: 2023年2月21日

5K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告