Created
September 9, 2019 09:18
-
-
Save jftuga/4c8b998ad4c581742f425b92d77765ba to your computer and use it in GitHub Desktop.
demonstrates how to either write to STDOUT or to a buffer in golang
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
// demonstrates how to either write to STDOUT or to a buffer | |
package main | |
import ( | |
"bufio" | |
"fmt" | |
"os" | |
) | |
func main() { | |
var f *os.File | |
var err error | |
var count int | |
fname := "testfile" | |
// change to either true|false | |
outputToScreen := false | |
if outputToScreen { | |
f = os.Stdout | |
} else { | |
f, err = os.OpenFile(fname,os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) | |
if err != nil { | |
fmt.Println("Error opening file") | |
return | |
} | |
} | |
writer := bufio.NewWriter(f) | |
count, err = writer.WriteString("alpha\n") | |
if err != nil { | |
fmt.Println("Error writing to buffer") | |
return | |
} | |
writer.Flush() | |
if !outputToScreen { | |
fmt.Printf("Wrote %d bytes to file: %s\n", count, fname) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment