Created
March 17, 2019 09:49
-
-
Save jnovikov/f9b33e628a3bfc98d07644129e2d3bd0 to your computer and use it in GitHub Desktop.
Input/Output examples
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 ( | |
"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