Created
April 6, 2014 16:24
-
-
Save AlexMocioi/10008287 to your computer and use it in GitHub Desktop.
Read big text data from SDIN in Go
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 "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)) | |
} | |
//---------------- | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.