Search code examples
filesortinggolines

Read in lines in a text file, sort, then overwrite file


I am trying to write a go function that will read in lines in a text file, sort them (alphabetize), and overwrite them back to the file. Right now, I am able to essentially emulate cat, but I can't seem to be able to manipulate the contents of the elements in read_line.

func sort() {

    ff, _ := os.OpenFile(file, os.O_RDWR, 0666)
    f := bufio.NewReader(ff)
    for {
        read_line, _ := f.ReadString('\n')
        fmt.Print(read_line)
        if read_line == "" {
            break
        }
    }
    ff.Close()
}

when i use ReadString, how can i store each line into a slice (or is there a better way to store them so i can manipulate them)? Then I would use the sort package in a manner similar to this:

sorted := sort.Strings(lines) 

then, to write to the file, i am using something similar to the following, although i have not included it because i have not yet gotten "sort" to work:

io.WriteString(ff, (lines + "\n"))

Thank you in advance for any suggestions!


Solution

  • For example,

    package main
    
    import (
        "bufio"
        "fmt"
        "os"
        "sort"
    )
    
    func readLines(file string) (lines []string, err os.Error) {
        f, err := os.Open(file)
        if err != nil {
            return nil, err
        }
        defer f.Close()
        r := bufio.NewReader(f)
        for {
            const delim = '\n'
            line, err := r.ReadString(delim)
            if err == nil || len(line) > 0 {
                if err != nil {
                    line += string(delim)
                }
                lines = append(lines, line)
            }
            if err != nil {
                if err == os.EOF {
                    break
                }
                return nil, err
            }
        }
        return lines, nil
    }
    
    func writeLines(file string, lines []string) (err os.Error) {
        f, err := os.Create(file)
        if err != nil {
            return err
        }
        defer f.Close()
        w := bufio.NewWriter(f)
        defer w.Flush()
        for _, line := range lines {
            _, err := w.WriteString(line)
            if err != nil {
                return err
            }
        }
        return nil
    }
    
    func main() {
        file := `lines.txt`
        lines, err := readLines(file)
        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }
        sort.Strings(lines)
        err = writeLines(file, lines)
        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }
    }