Reading files in bytes

I’m trying the below code, to read 2 files, and remove somelines from top and from bottom, but looks I’ve issue in reading the file.
my code is:

//file: clean.go
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strings"
)

func clean(files ...string) {
	for _, fn := range files {
		var f *os.File
		if f, err := os.OpenFile(fn, os.O_RDWR, 0); err != nil {
			log.Fatal("error", err)
		}
		defer func(f *os.File) {
			if err := f.Close(); err == nil {
				log.Fatal("error", err)
			}
		}(f)

		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[12 : len(lines)-5]
			} else {
				lines = lines[12 : len(lines)-6]
			}
			fmt.Println(fn, "has a total of", len(lines), "lines")
		}
	}
}

func main() {
	files := []string{"currentInvenory.csv", "currentTransactions.csv"}
	clean(files...)
}

But got this error:

.\clean.go:14:6: f declared but not used

you are declaring f again in the following line,

if f, err := os.OpenFile(fn, os.O_RDWR, 0); err != nil {

update your code like following

var f *os.File
var err error
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
    log.Fatal("error", err)
}
2 Likes
	for _, fn := range files {
		f, err := os.OpenFile(fn, os.O_RDWR, 0)
		if  err != nil {
			log.Fatal("error", err)
		}
		defer func(f *os.File) {
			if err := f.Close(); err == nil {
				log.Fatal("error", err)
			}
		}(f)

 		fileBytes, err := ioutil.ReadAll(f)
		if err != nil {
			log.Fatal("error", err)
		} 

		lines := strings.Split(string(fileBytes), "\n")
		if fn == "currentInvenory.csv" {
			lines = lines[12 : len(lines)-5]
		} else {
			lines = lines[12 : len(lines)-6]
		}
		fmt.Println(fn, "has a total of", len(lines), "lines")
		
	}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.