user2580104
user2580104

Reputation:

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.

  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?

Upvotes: 2

Views: 7362

Answers (2)

nosequeldeebee
nosequeldeebee

Reputation: 963

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()

Upvotes: 2

Gordon Childs
Gordon Childs

Reputation: 36169

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

Upvotes: 3

Related Questions