从Golang

时间:2015-06-19 14:05:34

标签: file go line

我正在尝试弹出文件的第一行,从而逐个减少文件行。 我删除第一行的实现如下

type FS struct {
    ...
    File       *os.File
}

//File creation ok...


func (fs *Fs) pop() []byte {
    var buf []string
    scanner := bufio.NewScanner(fs.File)
    //Reading lines
    for scanner.Scan() {
        line := scanner.Text()
        buf = append(buf, line)
    }
    //Writing from second line on the same file
    for s := 1; s < len(buf); s++ {
        fs.File.WriteString(fmt.Println(buf[s]))
    }
    //Commit changes
    fs.File.Sync()
    fs.File.Close()

    return []byte(buf[0])
}

我得到带有预期字符串的返回[]字节,但文件永远不会改变。 我在这里缺少什么?

1 个答案:

答案 0 :(得分:3)

例如,

package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
)

func popLine(f *os.File) ([]byte, error) {
    fi, err := f.Stat()
    if err != nil {
        return nil, err
    }
    buf := bytes.NewBuffer(make([]byte, 0, fi.Size()))

    _, err = f.Seek(0, os.SEEK_SET)
    if err != nil {
        return nil, err
    }
    _, err = io.Copy(buf, f)
    if err != nil {
        return nil, err
    }
    line, err := buf.ReadString('\n')
    if err != nil && err != io.EOF {
        return nil, err
    }

    _, err = f.Seek(0, os.SEEK_SET)
    if err != nil {
        return nil, err
    }
    nw, err := io.Copy(f, buf)
    if err != nil {
        return nil, err
    }
    err = f.Truncate(nw)
    if err != nil {
        return nil, err
    }
    err = f.Sync()
    if err != nil {
        return nil, err
    }

    _, err = f.Seek(0, os.SEEK_SET)
    if err != nil {
        return nil, err
    }
    return []byte(line), nil
}

func main() {
    fname := `popline.txt`
    f, err := os.OpenFile(fname, os.O_RDWR|os.O_CREATE, 0666)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer f.Close()
    line, err := popLine(f)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("pop:", string(line))
}
$ cat popline.txt
Lorem ipsum dolor sit amet, consectetur adipiscing elit, 
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
Ut enim ad minim veniam, 
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
Excepteur sint occaecat cupidatat non proident, 
sunt in culpa qui officia deserunt mollit anim id est laborum.

$ go run popline.go
pop: Lorem ipsum dolor sit amet, consectetur adipiscing elit, 

$ cat popline.txt
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
Ut enim ad minim veniam, 
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
Excepteur sint occaecat cupidatat non proident, 
sunt in culpa qui officia deserunt mollit anim id est laborum.

$