1 回答
TA贡献1808条经验 获得超4个赞
问题是if f, err := os.OpenFile( ...)定义了一个新变量f,这个新变量没有被使用。有两种可能的解决方案:
f, err := os.OpenFile(fn, os.O_RDWR, 0)
if err != nil {
log.Fatal("error", err)
}
或者
var f *os.File
var err error
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
log.Fatal("error", err)
}
所以,我现在的完整工作代码是:
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"sync"
)
func clean(files ...string) {
var wg sync.WaitGroup
for _, fn := range files {
wg.Add(1) // Launch several goroutines and increment the WaitGroup counter for each.
go worker(fn, &wg)
}
wg.Wait()
}
func main() {
files := []string{"currentInvenory.csv", "currentTransactions.csv"}
clean(files...)
}
func worker(fn string, wg *sync.WaitGroup) {
defer wg.Done()
var f *os.File
var err error
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
log.Fatal("error", err)
}
defer func() {
if err := f.Close(); err != nil {
log.Fatal("error", err)
}
}()
if fileBytes, err := ioutil.ReadAll(f); err != nil {
log.Fatal("error", err)
} else {
lines := strings.Split(string(fileBytes), "\n")
if fn == "currentInvenory.csv" {
lines = lines[11 : len(lines)-6]
} else {
lines = lines[11 : len(lines)-7]
}
fmt.Println(fn, "has a total of", len(lines), "lines")
if len(lines) > 0 {
var ctx = []byte{}
for _, s := range lines {
ctx = append(ctx, []byte(s)...)
}
ioutil.WriteFile(fn, ctx, 0644) // want (string, []byte, os.FileMode)
}
}
}
- 1 回答
- 0 关注
- 112 浏览
添加回答
举报