gpt4 book ai didi

file - 从 Golang 中的文本文件中删除第一行

转载 作者:IT王子 更新时间:2023-10-29 01:55:21 25 4
gpt4 key购买 nike

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

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])
}

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

最佳答案

pop the first line of a file and thus reduce the file lines one by one.


例如,

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, io.SeekStart)
if err != nil {
return nil, err
}
_, err = io.Copy(buf, f)
if err != nil {
return nil, err
}

line, err := buf.ReadBytes('\n')
if err != nil && err != io.EOF {
return nil, err
}

_, err = f.Seek(0, io.SeekStart)
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, io.SeekStart)
if err != nil {
return nil, err
}
return line, nil
}

func main() {
fname := `popline.txt`
f, err := os.OpenFile(fname, os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
defer f.Close()
line, err := popLine(f)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
fmt.Println("pop:", string(line))
}
$ cat popline.txtLorem 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.gopop: Lorem ipsum dolor sit amet, consectetur adipiscing elit, $ cat popline.txtsed 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.$ 

关于file - 从 Golang 中的文本文件中删除第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30940190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com