Skip to content

Instantly share code, notes, and snippets.

@asm-jaime
Created April 10, 2016 01:38
Show Gist options
  • Save asm-jaime/f8035f276ce4899a19472ebb1154b495 to your computer and use it in GitHub Desktop.
Save asm-jaime/f8035f276ce4899a19472ebb1154b495 to your computer and use it in GitHub Desktop.
Create, open, read and write string to file.
package main
import (
"bufio"
"fmt"
"os"
)
const file_path string = "output.txt"
var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)
//var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func main() {
create_write("dfdf")
open_write(" update!!!")
fmt.Print(open_read())
}
func create_write(data string) {
if data == "" {
fmt.Print("error! nothing to write!")
return
}
fo, err := os.Create(file_path)
if err != nil {
fmt.Print("error! create file failed!")
return
}
writer := bufio.NewWriter(fo)
defer fo.Close()
defer writer.Flush()
writer.WriteString(data)
}
func open_write(data string) {
if data == "" {
fmt.Print("error! nothing to write!")
return
}
foi, err := os.OpenFile(file_path, os.O_APPEND|os.O_WRONLY, os.ModePerm)
if err != nil {
fmt.Print("error! open file failed!")
return
}
writer := bufio.NewWriter(foi)
defer foi.Close()
defer writer.Flush()
writer.WriteString(data)
}
func open_read() string {
fi, err := os.Open(file_path)
if err != nil {
fmt.Print("error! open file failed!")
return ""
}
scanner := bufio.NewScanner(fi)
defer fi.Close()
scanner.Scan()
return scanner.Text()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment