Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing fdopen() and open() -> bad file descriptor

Tags:

c

file-io

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)

like image 894
Blub Avatar asked Dec 07 '11 14:12

Blub


1 Answers

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.

like image 147
Matt Joiner Avatar answered Sep 27 '22 23:09

Matt Joiner