Created
December 29, 2017 02:04
-
-
Save corvofeng/8901bcf557b46e8a234f0cfe613e2515 to your computer and use it in GitHub Desktop.
创建多个可供读写的临时文件, 并保证最终可以关闭
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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