这是代码实现,有个问题是更改某一行的内容后会影响下一个的内容.请大神帮我看一下
```go
package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"strings"
)
func main() {
fi, err := os.OpenFile("test.txt", os.O_RDWR, os.ModePerm)
if err != nil {
fmt.Println(err)
return
}
defer fi.Close()
reader := bufio.NewReader(fi)
lineCnt := 0
seekP := 0
for {
bs, _, err := reader.ReadLine()
if err == io.EOF {
fmt.Println(errors.New("读取完成"))
break
}
lineCnt = len(bs) + 2 //ReadLine 返回读取的长度不包含换行\r\n
if strings.Contains(string(bs), "hello") {
delBytes := make([]byte, 0) //编辑包含hello的行,需要先在该行写入ascii的127即删除符号,再写入新内容
for i := 0; i < lineCnt; i++ {
delBytes = append(delBytes, 127)
}
fi.WriteAt(delBytes, int64(seekP))
newStr := "hi\r\n"
fi.WriteAt([]byte(newStr), int64(seekP)) //在该行写入新内容
lineCnt = len([]byte(newStr)) //该行长度是新内容的长度
}
seekP += lineCnt
}
}
```
文本文件原始:
```
skdflksdlkfs
sjdfksdfksf
skjdkfj hello skjdfksjdfksjdkf
123
123
123
```
被程序修改后,可以看到修改行的下一行被加入了很多空格
```
skdflksdlkfs
sjdfksdfksf
hi
123
123
123
```
我是这样写的,测试文件:1.txt
this is the test file line 1
my name is hhh
#name=my year's old 18
Name=wangyunan
return restult
把第四行的 Name=wangyunan替换成Name=wang yu nan
代码:
package main
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
func main() {
oldFile := "./1.txt"
f, err := os.Open(oldFile)
if err != nil {
fmt.Println("文件打开失败")
return
}
defer f.Close()
buf := bufio.NewReader(f)
var rep = []string{"Name=wang yu nan"}
var result = ""
// 逐行读取
for {
a, _, err := buf.ReadLine()
if err == io.EOF {
fmt.Println("文件读取完毕")
break
}
if strings.Contains(string(a), "Name=wangyunan") {
result += strings.Join(rep, "") + "\n"
} else {
result += string(a) + "\n"
}
}
// 清空文件重新写入数据
fw, err := os.OpenFile(oldFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
fmt.Println("文件打开失败,请检查")
return
}
defer fw.Close()
w := bufio.NewWriter(fw)
w.WriteString(result)
if err != nil {
panic(err)
}
w.Flush()
}
最后输出:
this is the test file line 1
my name is hhh
#name=my year's old 18
Name=wang yu nan
return restult
#2
更多评论