[英]go - Create a new file in a specified path
嘗試以一種可移植的方式在$ GOPATH內的指定目錄中創建文件。
var FileName string = "Foci.db"
var Driver string = "sqlite3"
func Connect(fileName string) (*sql.DB, error) {
filePath, _ := filepath.Abs("../data/" + FileName)
// Create db if it doesn't exist
os.Open(filePath)
// Open existing db
return sql.Open(Driver, filePath)
}
但是,這似乎並沒有像我希望的那樣在數據目錄中創建文件。 難道我做錯了什么?
Open()
不會創建文件。 嘗試使用Create()
代替。
您可能正在尋找使用os.OpenFile
就像其他提到的那樣,您可以在Create()
之后使用Create()
,然后使用Open()
。
如果您需要高度的特異性,則os.OpenFile
很有用,因為它允許您一次設置路徑,標志(只讀,只寫等)和權限。
例如。
f, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
//handle error
}
defer f.Close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.