File tree Expand file tree Collapse file tree 2 files changed +57
-1
lines changed Expand file tree Collapse file tree 2 files changed +57
-1
lines changed Original file line number Diff line number Diff line change 1+ package main
2+
3+ import (
4+ "bufio"
5+ "fmt"
6+ "os"
7+ )
8+
9+ // Buffered I/O is an efficient way to handle files.
10+ // It is faster to write a big chunk of data than many small chunks.
11+ // The bufio-package contains many more useful functions. Explore it!
12+
13+ // Writing a textfile
14+ func WriteFile (filename string ) {
15+ f , err := os .Create (filename ) // creating the textfile
16+ if err != nil {
17+ panic (err .Error ()) // error handling
18+ }
19+ defer f .Close ()
20+ w := bufio .NewWriter (f ) // new writer with default size (4096 Bytes)
21+ var text string
22+ for i := 0 ; i < 100 ; i ++ {
23+ text = fmt .Sprintf ("%s %02d\t " , "Message" , i )
24+ w .WriteString (text ) // write to the buffer
25+ }
26+ w .Flush () //write everything to the underlying writer. Never forget this!
27+ }
28+
29+ // Reading a textfile
30+ func ReadFile (filename string ) {
31+ f , err := os .Open (filename ) // open the textfile
32+ if err != nil {
33+ panic (err .Error ()) // error handling
34+ }
35+ defer f .Close ()
36+ scanner := bufio .NewScanner (f )
37+ for scanner .Scan () {
38+ fmt .Println (scanner .Text ())
39+ }
40+ if err := scanner .Err (); err != nil {
41+ panic (err .Error ()) // error handling
42+ }
43+ }
44+
45+ func main () {
46+ const filename = "Strings.txt"
47+ WriteFile (filename )
48+ fmt .Println ("100 useless strings written to the file..." )
49+ fmt .Println ("Now we will read the file." )
50+ fmt .Println ()
51+ ReadFile (filename )
52+ }
Original file line number Diff line number Diff line change 1818
1919* ** LinkedList** : a singly linked list
2020
21- * Level: Intermediate*
21+ * Level: Intermediate*
22+
23+ * ** BufIO** : a simple introduction to buffered i/o
24+
25+ * Level: Beginner*
You can’t perform that action at this time.
0 commit comments