[Solved] Reading files in bytes [closed]


Thanks to the comments above, the problem is if f, err := os.OpenFile( ...) defines a new variable f, this new variable is not used. There are two potential solutions:

f, err := os.OpenFile(fn, os.O_RDWR, 0)
if err != nil {
    log.Fatal("error", err)
}

Or

var f *os.File
var err error
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
    log.Fatal("error", err)
}

So, my full working code now is:

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

}

solved Reading files in bytes [closed]