Skip to content

Instantly share code, notes, and snippets.

@AlexMocioi
Created April 6, 2014 16:24
Show Gist options
  • Save AlexMocioi/10008287 to your computer and use it in GitHub Desktop.
Save AlexMocioi/10008287 to your computer and use it in GitHub Desktop.
Read big text data from SDIN in Go
package main
import "fmt"
import "bufio"
import "os"
func main() {
f, _ := os.Create("outputgo.txt")
reader := bufio.NewReader(os.Stdin)
for {
line, err := reader.ReadString('\n')
if err != nil {
fmt.Println("%s", line)
return
}
f.WriteString(line)
}
}
//------------
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Println(scanner.Text()) // Println will add back the final '\n'
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
}
//-----------------
// Create a buffer to hold the stream data
data := make([]byte, 5000)
// Read data from stdin in a loop
for {
_, err = os.Stdin.Read(data)
if err != nil {
panic(err)
}
index := bytes.Index(data, []byte("\n"))
data = data[:index]
var myStruct MyStruct
err = json.Unmarshal(data, &myStruct)
if err != nil {
panic(err)
}
//(Do something with myStruct)
}
//-----------------
import "os"
import "log"
import "bufio"
func main() {
reader := bufio.NewReader(os.Stdin)
for {
line, err := reader.ReadString('\n')
if err != nil {
// You may check here if err == io.EOF
break
}
log.Println(line)
}
}
//---------------
package main
import "os"
import "log"
import "io/ioutil"
func main() {
bytes, err := ioutil.ReadAll(os.Stdin)
log.Println(err, string(bytes))
}
//----------------
@hitzhangjie
Copy link

If I input something, then press backspace, then keep inputing characters.

ioutil.ReadAll(os.Stdin) will contains some special characters, while I don't know how to delete them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment