Bad File Descriptor?

3,292 views
Skip to first unread message

Xiphos

unread,
Aug 19, 2010, 8:44:40 PM8/19/10
to golang-nuts
Hi Everyone,

I am just trying something really simple here: write something into a
file. It worked this morning on a windows machine using the windows
port of go. Now I am home and trying it on my Ubuntu 10.04. I am
getting a Bad File Descriptor err. Tried many things and nothing
worked... Here is the code, plz anyone have a look...

Thank you so very much~

// It failed on the Only Write call in the code. The folder exists.
Permission of the folder is: drwxr-xr-x

package main

import (
"strings"
"os"
)

func main() {
file, err := os.Open("golang.org/golang.org_start_page.html",
os.O_CREATE, 0644)

if err != nil {
panic(err)
}

const NBUF = 512
var buf [NBUF]byte

reader := strings.NewReader("abcdefghijklmnopqrstuvwxyz")
nr, er := reader.Read(&buf)

if er == nil {
if nw, ew := file.Write(buf[0:nr]); nw != nr {
panic(ew)
}
} else {
panic(er)
}
}

Xiphos

unread,
Aug 19, 2010, 8:49:19 PM8/19/10
to golang-nuts
NVM I figured it out. You have to or the O_CREATE with one of the flag
that allows to write.

drew m

unread,
Aug 20, 2010, 3:20:06 PM8/20/10
to golang-nuts
and what would that flag be?

Asher Samuel

unread,
May 4, 2026, 7:21:50 PM (8 days ago) May 4
to golang-nuts
still waiting for what the flag is 😭

Brian Candler

unread,
May 5, 2026, 3:28:34 AM (8 days ago) May 5
to golang-nuts
You've just replied to a thread which is more than 15 years old, relating to operating systems and Go versions of the same vintage.

I believe this thread was prior to the release of Go 1, because the call to os.Open() as shown doesn't even compile in current versions of Go: it now only accepts a single string argument.  The correct answer for today is to use os.Create().  Similarly, reader.Read no longer accepts a pointer.

However,  the answer to the 15-year old question is still available in the manpage of open:

       The  open()  system  call  opens  the file specified by pathname.  If the specified file does not exist, it may optionally (if O_CREAT is specified in
       flags) be created by open().
...
       The argument flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR.  These request opening the  file  read-only,  write-
       only, or read/write, respectively.

That is, if you were making a low-level open() call, you could set the mode to be O_WRONLY|O_CREAT or O_RDWR|O_CREAT depending on what you want to do with the file descriptor.
Reply all
Reply to author
Forward
0 new messages