sách gpt4 ai đã đi

file - 如何在Go中附加到文件的开头?

In lại 作者:行者123 更新时间:2023-12-01 22:41:11 25 4
mua khóa gpt4 Nike

我想附加到文件的开头。不要误会我的意思,我可以附加它,但是我希望最后写入的字符串在文件的顶部(第一行)。

1 Câu trả lời

此示例程序“追加”到文件的开头
它假设文件内容是带有行尾的行,并且
没有其他东西正在修改文件
(可能还有其他一些假设。.这是一个简单的示例)

gói chính

nhập khẩu (
"bufio"
"os"
)

hàm main() {
addline := "aaa first\n"
// make a temporary outfile
outfile, err := os.Create("newfoo.txt")

nếu err != nil {
panic(err)
}

defer outfile.Close()

// open the file to be appended to for read
f, err := os.Open("foo.txt")

nếu err != nil {
panic(err)
}

defer f.Close()

// append at the start
_, err = outfile.WriteString(addline)
nếu err != nil {
panic(err)
}
scanner := bufio.NewScanner(f)

// read the file to be appended to and output all of it
for scanner.Scan() {

_, err = outfile.WriteString(scanner.Text())
_, err = outfile.WriteString("\n")
}

if err := scanner.Err(); err != nil {
panic(err)
}
// ensure all lines are written
outfile.Sync()
// over write the old file with the new one
err = os.Rename("newfoo.txt", "foo.txt")
nếu err != nil {
panic(err)
}
}

关于file - 如何在Go中附加到文件的开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63969610/

25 4 0
Bài viết được đề xuất: go - GOPATH 的正确设置是什么?
Bài viết được đề xuất: Thuộc tính tìm nạp dữ liệu cốt lõi - cơ bản
Bài viết được đề xuất: arrays - 在字节数组上使用json.Unmarshal()时出现问题
Bài viết được đề xuất: go - 将方法参数传递给函数
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com