err := os.Create(“output.txt") ! // close out on exit and check for its returned error defer func() { if err := out.Close(); err != nil { panic(err) } }() ! // make a write buffer w := bufio.NewWriter(out) ! // make a buffer to keep chunks that are read buf := make([]byte, 1024) for { // read a chunk n, err := r.Read(buf) ! if n == 0 { break } ! // write a chunk if _, err := w.Write(buf[:n]); err != nil { panic(err) } } ! if err = w.Flush(); err != nil { panic(err) }
scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { fmt.Println(scanner.Text()) // Println will add back the final '\n' } ! // Scan words const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n" scanner := bufio.NewScanner(strings.NewReader(input)) // Set the split function for the scanning operation. scanner.Split(bufio.ScanWords) // Count the words. count := 0 for scanner.Scan() { count++ } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading input:", err) } fmt.Printf("%d\n", count)