The “bad file descriptor” error in Go occurs when you operate on a closed, invalid, or improperly initialized file descriptor.
To fix the “bad file descriptor” error in Golang, “ensure you have correctly opened the file” or “ensure you are not using a closed file descriptor”.
Here is the step-by-step guide to fix the issue.
Solution 1: Make sure you have correctly opened the file
Before performing any operations on a file, ensure it is adequately opened using the os.Open() or os.Create() functions. These functions return a file descriptor that you can use for further operations.
package main
import (
"log"
"os"
)
func main() {
file, err := os.Open("data.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
}
Solution 2: Ensure you are not using a closed file descriptor
If you try to operate on a file that has already been closed using the Close() method, you will encounter a “bad file descriptor” error. Double-check your code to avoid closing the file descriptor before performing the intended operation.
Solution 3: Check for concurrent access
Using goroutines to access the same file descriptor concurrently can lead to issues such as the “bad file descriptor” error. If you need to access the same file from multiple goroutines, consider using synchronization mechanisms like sync.Mutex to prevent concurrent access.
var mu sync.Mutex
func writeFile(data []byte) {
mu.Lock()
defer mu.Unlock()
}
Solution 4: Inspecting the error
If an error occurs while working with a file descriptor, inspect the error to understand the issue better. Use the error value returned by file operations to handle specific cases or log the error for further inspection.
package main
import (
"fmt"
"io"
"log"
"os"
)
func main() {
file, err := os.Open("my_text_file.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
buffer := make([]byte, 1024)
for {
n, err := file.Read(buffer)
if err != nil {
if err == io.EOF {
fmt.Println("Reached end of the file")
break
} else {
log.Println("Error reading from file:", err)
break
}
}
fmt.Print(string(buffer[:n]))
}
}
Output
This is the first line.
This is the second line.
This is the third line.
Reached end of the file
This example opens “my_text_file.txt” for reading, creates a buffer, and reads the file content in a loop. The provided code snippet is used to handle the io.EOF error (end of the file) and any other errors that may occur during reading. The read data is printed to the console.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.