Created
April 11, 2012 14:15
-
-
Save billzhuang/2359559 to your computer and use it in GitHub Desktop.
read/write lines for a text file used for inner contacts
This file contains hidden or 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 ( | |
"os" | |
"bufio" | |
"bytes" | |
"io" | |
"fmt" | |
"strings" | |
) | |
func readLines(path string) (lines []string, err error) { | |
file, err := os.Open(path) | |
if err != nil { | |
return | |
} | |
defer file.Close() | |
reader := bufio.NewReader(file) | |
for err == nil { | |
var line string | |
line, err = reader.ReadString('\n') | |
line = stripNewline(line) | |
if err == nil || line != "" { | |
lines = append(lines, line) | |
} | |
} | |
if err == io.EOF { | |
err = nil | |
} | |
return | |
} | |
func writeLines(lines []string, path string) (err error) { | |
var ( | |
file *os.File | |
) | |
if file, err = os.Create(path); err != nil { | |
return | |
} | |
defer file.Close() | |
//writer := bufio.NewWriter(file) | |
for _,item := range lines { | |
//fmt.Println(item) | |
_, err := file.WriteString(strings.TrimSpace(item) + "\n"); | |
//file.Write([]byte(item)); | |
if err != nil { | |
//fmt.Println("debug") | |
fmt.Println(err) | |
break | |
} | |
} | |
/*content := strings.Join(lines, "\n") | |
_, err = writer.WriteString(content)*/ | |
return | |
} | |
func stripNewline(s string) string { | |
switch { | |
case strings.HasSuffix(s, "\r\n"): | |
return s[:len(s)-2] | |
case strings.HasSuffix(s, "\n"): | |
return s[:len(s)-1] | |
} | |
return s | |
} | |
func main() { | |
lines, err := readLines("foo.txt") | |
if err != nil { | |
fmt.Println("Error: %s\n", err) | |
return | |
} | |
for _, line := range lines { | |
fmt.Println(line) | |
} | |
//array := []string{"7.0", "8.5", "9.1"} | |
err = writeLines(lines, "foo2.txt") | |
fmt.Println(err) | |
} |
make([]byte, 0, 1024) creates a slice structure with length 0 and a capacity of 1024
previous make([]byte, 1024) is wrong.
make([]byte, 0) also wrong
use reader.ReadString instead of bytes.Buffer
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it also meet quite a lot of ^@ when view in VI @mac osx 10.7
just cuz buffer.Write(part) use append mode, so we should allocate make([]byte, 0) to pass when we try to create new Buffer object