Go語言程式以只寫模式開啟檔案
在 Go 語言中,我們可以使用 OS 函式 os.OpenFile()、os.Create() 和 ioutil.WriteFile 來開啟一個只寫檔案。這裡我們將看到三個不同的示例來理解這些函式的功能。在第一個程式中,我們將使用 OpenFile() 函式,而在第二個和第三個程式中,我們將分別使用 writeFile() 和 create() 函式。
語法
func WriteFile(filename string, data []byte, perm os.FileMode) error
WriteFile() 函式位於 ioutil 包中,用於將資料寫入檔案。該函式接受要寫入資料的檔名、位元組資料切片和許可權作為引數。
os.Openfile()
此函式是 os 包的一部分。它用於開啟檔案以進行讀取。它接受一個輸入,即要開啟的檔名。
os.create()
此函式來自 os 包。它有助於建立新檔案。檔名作為函式的輸入給出。
演算法
匯入所需的包
建立主函式
使用內部函式開啟檔案
列印檔案是否已開啟
示例 1
在本示例中,我們將編寫一個 Go 語言程式,使用 os 包中的函式以只寫模式開啟檔案。
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.OpenFile("sample.txt", os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
panic(err)
} else {
fmt.Println("The file is successfully opened in write-only mode")
}
defer file.Close()
}
輸出
The file is successfully opened in write-only mode
示例 2
在本示例中,我們將編寫一個 Go 語言程式,使用 os 包中的函式以只寫模式開啟檔案。
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Create("newfile.txt")
if err != nil {
panic(err)
} else {
fmt.Println("The file is successfully opened in write-only mode")
}
defer file.Close()
}
輸出
The file is successfully opened in write-only mode
示例 3
在本示例中,我們將編寫一個 Go 語言程式,使用 ioutil 包中的 WriteFile() 函式以只寫模式開啟檔案。
package main
import (
"fmt"
"io/ioutil"
)
func main() {
err := ioutil.WriteFile("newfile.txt", []byte("Hello, World!"), 0644)
if err != nil {
panic(err)
} else {
fmt.Println("The file is successfully opened in write-only mode")
}
}
輸出
The file is successfully opened in write-only mode
結論
我們已經成功編譯並執行了一個 Go 語言程式,以只寫模式開啟檔案,並附帶示例。在本文中,我們學習瞭如何使用 Go 中的不同示例以只寫模式開啟檔案。我們瞭解瞭如何使用 os.OpenFile、os.Create 和 ioutil.WriteFile 來實現這一點。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP