I'm learning about file descriptors and I wrote this code:
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> int fdrd, fdwr, fdwt; char c; main (int argc, char *argv[]) { if((fdwt = open("output", O_CREAT, 0777)) == -1) { perror("Error opening the file:"); exit(1); } char c = 'x'; if(write(fdwt, &c, 1) == -1) { perror("Error writing the file:"); } close(fdwt); exit(0); }
, but I'm getting: Error writing the file:: Bad file descriptor
I don't know what could be wrong, since this is a very simple example.
In general, when "Bad File Descriptor" is encountered, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons: The fd is already closed somewhere. The fd has a wrong value, which is inconsistent with the value obtained from socket() api.
When you don't allow the code to perform the functions related to the file descriptors and the methods used, a Bad File Descriptor Error arises in Python, indicating the wrong way of implementing the code.
A file descriptor is a number that uniquely identifies an open file in a computer's operating system. It describes a data resource, and how that resource may be accessed. When a program asks to open a file — or another data resource, like a network socket — the kernel: Grants access.
Try this:
open("output", O_CREAT|O_WRONLY, 0777)
I think O_CREAT
alone is not enough. Try adding O_WRONLY
as flag to the open command.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With