创建 – 在指定路径中创建一个新文件

huangapple go评论68阅读模式
英文:

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)
    // 如果数据库文件不存在,则创建
    os.Open(filePath)
    // 打开现有的数据库文件
    return sql.Open(Driver, filePath)
}

然而,这似乎没有按照我希望的方式在data目录中创建文件。我做错了什么吗?

英文:

Trying to make a portable way to create a file in a specified directory within my $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?

答案1

得分: 3

Open()不会创建文件。请尝试使用Create()

英文:

Open() won't create the file. Try Create() instead.

答案2

得分: 2

你可能想要使用os.OpenFile

正如其他人提到的,你可以使用Create(),然后在创建后使用Open()

如果你需要高度的特定性,os.OpenFile可能很有用,因为它允许你一次性设置路径、标志(只读、只写等)和权限。

例如:

f, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
    //处理错误
}

defer f.Close()
英文:

You were probably looking to use os.OpenFile

As the other poster mentioned you can use Create() and then Open() after it's created.

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.

Eg.

f, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
	//handle error
}

defer f.Close()

huangapple
  • 本文由 发表于 2016年11月20日 05:42:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/40698237.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定