Skip to content

Instantly share code, notes, and snippets.

@billzhuang
Created April 11, 2012 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save billzhuang/2359559 to your computer and use it in GitHub Desktop.
Save billzhuang/2359559 to your computer and use it in GitHub Desktop.
read/write lines for a text file used for inner contacts
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)
}
@billzhuang
Copy link
Author

update stackoverflow version here: http://stackoverflow.com/questions/5884154/golang-read-text-file-into-string-array-and-write/10107708#10107708

cuz go1 has some break change, so add a gist here

@billzhuang
Copy link
Author

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

@billzhuang
Copy link
Author

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

@billzhuang
Copy link
Author

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