user1243746
user1243746

Reputation:

When to close a file?

Is necessary to close a file when you only want create it? I'm supposed that it's only necessary in case of reading or writing.

_, err := os.OpenFile(name, os.O_CREATE, 0640)

Upvotes: 2

Views: 134

Answers (2)

John Watts
John Watts

Reputation: 8875

Will it work? Yes. The file will be created.

Should you do it? No. It is a bad idea in general even though you can get away with it sometimes.

Opening a file allocates resources like a file handle to your process. You should close it to free those resources. Otherwise they will be unavailable until the process dies.

Upvotes: 4

Guffa
Guffa

Reputation: 700302

When you create the file you also open it, so you should close it.

Upvotes: 1

Related Questions