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.
main
. You also declarec
twice, you don't need thechar
inchar c
the second time. At the same time, the second declaration ofc
in the middle of the function is only valid in C99, but you declaremain
without a return type -- which is invalid in C99, which eliminates the "implicit int" rule that was present in C89 and earlier versions of C. Most compilers should issue warnings for that, some will throw an error and refuse to compile. – Caloric