Last active
February 1, 2017 10:28
-
-
Save AndrienkoAleksandr/cfca6dd1b70d2bb3e37c1ddd9bcca44c to your computer and use it in GitHub Desktop.
"How to" write and read from temp file.
This file contains hidden or 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" | |
"io/ioutil" | |
) | |
//todo Sync it's important!!!! file.Sync() | |
func main() { | |
fmt.Println("Try to create temp file"); | |
file, createFileErr := ioutil.TempFile(os.TempDir(), "tempFilePrefix"); | |
check("Failed to create temp file", createFileErr); | |
fmt.Println("Temp file successfully created.") | |
defer func() { | |
file.Close(); | |
os.Remove(file.Name()) | |
}() | |
d1 := []byte("some test text for file") | |
writeToFileError := ioutil.WriteFile(file.Name(), d1, 0644) | |
file.Sync() | |
check("Failed to write information to File", writeToFileError) | |
fmt.Println("temp file path", file.Name()) | |
reader := ioutil.NopCloser(file); | |
defer reader.Close() | |
buffer, readErr := ioutil.ReadAll(file); | |
if readErr != nil { | |
check("Failed to read inforation from file", readErr) | |
} | |
fmt.Println(string(buffer)) | |
fmt.Println("Read from file completed", reader) | |
} | |
func check(message string, e error) { | |
if e != nil { | |
fmt.Errorf(message) | |
panic(e) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment