Skip to content

Instantly share code, notes, and snippets.

@jnovikov
Created March 17, 2019 09:49
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 jnovikov/f9b33e628a3bfc98d07644129e2d3bd0 to your computer and use it in GitHub Desktop.
Save jnovikov/f9b33e628a3bfc98d07644129e2d3bd0 to your computer and use it in GitHub Desktop.
Input/Output examples
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
)
func main() {
// Read file with .Read()
f, err := os.OpenFile("a.txt", os.O_RDONLY, 0)
if err != nil {
panic(err)
}
stat, _ := f.Stat()
b := make([]byte, stat.Size())
n, err := f.Read(b)
if err != nil {
panic(err)
}
fmt.Println("Readed ", n, " bytes")
fmt.Println(string(b))
//Read by byte
f, err = os.OpenFile("a.txt", os.O_RDONLY, 0)
if err != nil {
panic(err)
}
fileContent := make([]byte, 0)
b = make([]byte, 1)
_, err = f.Read(b)
if err != nil {
panic(err.Error())
}
for err == nil {
fileContent = append(fileContent, b[0])
_, err = f.Read(b)
}
fmt.Println(string(fileContent))
//Read file with ReadAll
f, err = os.OpenFile("a.txt", os.O_RDONLY, 0)
if err != nil {
panic(err)
}
content, err := ioutil.ReadAll(f)
if err != nil {
panic(err)
}
fmt.Println(string(content))
// Read file
//content, err := ioutil.ReadFile("a.txt")
// Read one line from keyboard
reader := bufio.NewReader(os.Stdin)
s, _ := reader.ReadString('\n')
fmt.Println(s)
// Read two ints from file
f, err = os.Open("b.txt")
if err != nil {
panic(err)
}
var x, y int
fmt.Fscanln(f, &x, &y)
fmt.Println(x + y)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment