The solution to golang bad file descriptor problem
- 2020-06-19 10:33:05
- OfStack
Found the problem
In golang, the above error occurred while writing to a file. First of all, reproduce the problem.
package main
import (
"os"
"fmt"
)
func main() {
file, err := os.Open("a.txt")
if err != nil {
fmt.Println(err)
}
defer file.Close()
content:=[]byte("Go is an open source programing language that makes it easy to build simple,reliable,and efficient software")
_, err = file.Write(content)
if err != nil {
fmt.Println(err)
}
}
This will cause an error to run
write a.txt: bad file descriptor
. What is the reason? In fact this and
os.Open()
Functions are concerned, so let's look at the Open() function.
func Open(name string) (*File,error) {
return OpenFile(name, O_RDONLY, 0)
}
As you can see, the default mode for the Open function to open a file is read-only, so you are not allowed to write to an open file. The value of the second parameter passed into the OpenFile function can be:
[
Parameter name meaning
O_RDONLY opens the read-only file
O_WRONLY opens write only files
O_RDWR opens to read and write files
O_APPEND appends data to the end of the file when it writes to it
O_CREATE Creates a new file if one does not exist
The O_EXCL file must not exist, and then a new file is created
O_SYNC turns on synchronization I/0
The O_TRUNC file can be truncated when opened
The solution
Now that we know why, the solution is simply to change the way the file is read. The following cases:
package main
import (
"os"
"fmt"
)
func main() {
file, err := os.OpenFile("a.txt", os.O_APPEND|os.O_WRONLY, os.ModeAppend)
if err != nil {
fmt.Println(err)
}
defer file.Close()
content:=[]byte("Go is an open source programing language that makes it easy to build simple,reliable,and efficient software")
_, err = file.Write(content)
if err != nil {
fmt.Println(err)
}
}
conclusion