"invalid argument" coming from os.(*File).Read

5,049 views
Skip to first unread message

skil...@psiimage.com

unread,
May 25, 2016, 11:51:56 AM5/25/16
to golang-nuts
I started off with trying to parse a CSV file with encoding/csv.(*Reader).Read, but I was receiving an "invalid argument" error from that call.  I then tried just using os.(*File).Read, but I'm getting the same error when I try to read a file into a buffer.  Below is the code I am using:

package main

import (
"fmt"
"os"
)


func main() {
filename := os.Args[1]
fmt.Println("Filename:", filename)
var f *os.File
if f, err := os.Open(filename); err == nil {
if f == nil {
panic(fmt.Errorf("os.Open did not return an error but file did not open"))
}
defer func() {
if err := f.Close(); err != nil {
panic(err)
}
}()
} else {
panic(err)
}
b := make([]byte, 1024)
if _, err := f.Read(b); err == nil {
fmt.Println(string(b))
} else {
panic(err)
}
}


os.(*File).Read is returning an "invalid argument" error, which according to the documentation I am reading here means that the receiver (I believe that is f) is nil, but I check for that!  I'm getting this behavior with any file I try and on both Arch Linux x86 and Windows 10 x86_64.  I'm hoping I'm overlooking something simple; any suggestions?

I tried the code I am using to read a CSV and replaced the *os.File returned by os.Open with the result of strings.NewReader (as exemplified in the encoding/csv documentation here) and then it works.  What do I have to do for it to work with a file?

Thomas Bushnell, BSG

unread,
May 25, 2016, 11:53:28 AM5/25/16
to skil...@psiimage.com, golang-nuts
The f you are declaring in the call to Open is shadowing the one at top level of the function, so that the one in the Read call.

--
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...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Sean Killian

unread,
May 25, 2016, 12:29:28 PM5/25/16
to Thomas Bushnell, BSG, golang-nuts
That was it, thank you!
--


Thank you,

Sean Killian
3494 Progress Drive, Suite A
Bensalem, PA  19020
skil...@psiimage.com
(215) 604-1330 x200

Dave Cheney

unread,
May 25, 2016, 6:18:20 PM5/25/16
to golang-nuts, tbus...@google.com, skil...@psiimage.com
go vet can detect problems like this.
Reply all
Reply to author
Forward
0 new messages