Michael,

func openFile(s string, file *os.File) {
file, err := os.Open(s)
if err != nil {
log.Fatal(err)
}
    defer file.Close()
}

You open the file and when the function exits, close the file.

Peter

On Wednesday, June 21, 2017 at 12:44:36 PM UTC, Michael Dwyer wrote:
>
> Hello to all,
>
> My first time posting questions here, so please bear with me, I'm willing 
> to learn.
>
> I have a simple piece of code, which opens a file, reads the contents and 
> counts the number of lines in the file.
> What I am attempting to do is to refactor the code. The error occurs when 
> I read the file, when the program terminates
> zero lines were read.
>
> I have attempted to resolve this problem to no avail, which is why I am 
> reaching out for help.
> The code that is commented out works as expected.
>
> package main
>  
> import (
> "flag"
> "bufio"
> "fmt"
> "log"
> "os"
> )
>
> func cli() string {
> flag.Parse()
> return flag.Arg(0)
> }
>
> func openFile(s string, file *os.File) {
> file, err := os.Open(s)
> if err != nil {
> log.Fatal(err)
> }
>     defer file.Close()
> }
>
> func main() {
> fname := cli()
> /***
> f, err := os.Open(fname)
> if err != nil {
> log.Fatal(err)
> }
> defer f.Close()
> */
> var f *os.File
> openFile(fname, f)
> ireader := bufio.NewReader(f)
> scanner := bufio.NewScanner(ireader)
> lcounter := 0
> for scanner.Scan() {
> lcounter++
> }
> fmt.Printf("# lines read : %d\n", lcounter)
> }
>
> Thanks in advance, I do appreciate any help in resolving this.
>
>
> THANX(MKD).
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to