[英]go - Create a new file in a specified path
Trying to make a portable way to create a file in a specified directory within my $GOPATH. 尝试以一种可移植的方式在$ 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)
}
However, this doesn't seem to create the file in the data directory as I hoped. 但是,这似乎并没有像我希望的那样在数据目录中创建文件。 Am I doing something wrong? 难道我做错了什么?
Open()
won't create the file. Open()
不会创建文件。 Try Create()
instead. 尝试使用Create()
代替。
You were probably looking to use os.OpenFile 您可能正在寻找使用os.OpenFile
As the other poster mentioned you can use Create()
and then Open()
after it's created. 就像其他提到的那样,您可以在Create()
之后使用Create()
,然后使用Open()
。
If you need high specificity, os.OpenFile
can be useful as it allows you to set the path, flags (read only, write only etc.) and permissions all in one go. 如果您需要高度的特异性,则os.OpenFile
很有用,因为它允许您一次设置路径,标志(只读,只写等)和权限。
Eg. 例如。
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.