int source = open("hi", O_CREAT | O_RDONLY);
int dest = open("resultfile", O_CREAT | O_RDWR | O_TRUNC);
FILE* source1 = fdopen(source, "r");
FILE* dest1 = fdopen(dest, "w+");
// outside of a testcase I would write something into 'resultfile' here
close(source);
close(dest);
fclose(source1);
fclose(dest1);
int sourcef = open("resultfile", O_RDONLY);
printf(strerror(errno)); // <--- Bad file descriptor
I don't understand why? How can I successfully mix stream based IO with open()?
A library that I'm working with only accepts an integer fd (and the library is internally responsible for closing it, presumably with close()), but I still need to work with the file, and I don't see how that is properly possible without the f() calls like (fread(), ftell() etc)
fclose
calls close
for you. If you want to keep the fd around after calling fclose
, dup
the fd first.
int fd = open(...);
int fd2 = dup(fd);
FILE *fp = fdopen(fd2);
fclose(fp);
// fd is still valid.
The bad file descriptor error message in your example is lingering from the fclose(dest1)
call.
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