Skip to content

Instantly share code, notes, and snippets.

@corvofeng
Created December 29, 2017 02:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save corvofeng/8901bcf557b46e8a234f0cfe613e2515 to your computer and use it in GitHub Desktop.
Save corvofeng/8901bcf557b46e8a234f0cfe613e2515 to your computer and use it in GitHub Desktop.
创建多个可供读写的临时文件, 并保证最终可以关闭
package main
import (
"fmt"
"os"
)
// Creat Many files to read or write
// file name likes `tmp-file_ok-0``
func FileCreator(fileCnt int) {
// Now we create the files
fileArr := make([]*os.File, fileCnt)
var err error
for i := 0; i < fileCnt; i++ {
fileArr[i], err = os.OpenFile(fmt.Sprintf("tmp-%s-%d", "file_ok", i),
os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
panic(err)
}
// after a func end, the file should be closed
defer fileArr[i].Close()
}
}
// With this gist, you could create many files to write and
// use defer to close them.
func main() {
FileCreator(3)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment