Go語言程式:以追加模式開啟檔案,檔案不存在則建立
在 Go 語言中,我們可以使用 `os` 包的 `os.OpenFile` 函式和 `ioutil` 包的 `ioutil.WriteFile()` 函式來追加檔案。然後,我們將使用 `WriteString()` 函式來列印結果。在這篇文章中,我們將學習如何建立一個 Go 語言程式,以追加模式開啟檔案,如果檔案不存在則建立。
語法
os.OpenFile(name/path string, flag int, perm FileMode)
`OpenFile()` 函式位於 `os` 包中。該函式接受三個引數。一個是待開啟的檔名,後跟用於開啟檔案的整數型別指令。這表示檔案開啟的模式,例如只讀、只寫、讀寫模式等。該函式返回兩個值作為結果,一個是可以在其上執行不同操作(例如寫入或追加)的檔案(基於傳遞給函式的檔案模式),另一個是錯誤檔案。
ioutil.WriteFile()
在 Go 中,`WriteFile` 屬於 `ioutil` 包,包含三個引數:第一個是寫入資料的檔名;第二個是要寫入的資料;第三個是檔案許可權。如果函式成功執行,資料將被寫入檔案。
file.WriteString()
在 Go 程式語言中,`WriteString` 方法用於將字串寫入檔案。字串作為引數 `str` 傳遞給函式。
演算法
匯入所需的包。
建立一個主函式
使用內建函式在主函式中以追加模式開啟檔案
列印檔案是否成功開啟
示例 1
在這個例子中,我們將編寫一個 Go 語言程式,使用 `os` 包的函式以追加模式開啟檔案。我們將使用 “`os.OpenFile`” 函式以追加模式開啟檔案。
package main
import (
"fmt"
"os"
)
func main() {
// Open the file in append mode
file, err := os.OpenFile("newfile.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
// Write to the file
_, err = file.WriteString("Hello, World!\n")
if err != nil {
fmt.Println(err)
} else {
fmt.Println("The file is successfully opened in append mode")
}
}
輸出
The file is successfully opened in append mode
示例 2
在這個例子中,我們將編寫一個 Go 語言程式,使用 `ioutil` 包中的各種函式以追加模式開啟檔案。我們將使用 `ioutil` 包的 `WriteFile()` 函式來實現結果。
package main
import (
"fmt"
"io/ioutil"
)
func main() {
// Write to the file
err := ioutil.WriteFile("sample.txt", []byte("Hello, World!\n"), 0644)
if err != nil {
fmt.Println(err)
} else {
fmt.Println("The file is successfully opened in append mode")
}
}
輸出
The file is successfully opened in append mode
結論
我們已經成功編譯並執行了一個 Go 語言程式,該程式以追加模式開啟檔案,並附帶示例。我們查看了兩個示例:使用 “`os`” 包和使用 “`ioutil`” 包。這兩個示例都為處理檔案提供了高階介面,並簡化了檔案 I/O 操作。
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP