Mixing fdopen () and open () & # 8594; file descriptor

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 do not understand why? How can I successfully combine open-source IO with open ()?

The library I work in only accepts the 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 this is possible without calling f ( ) like (fread (), ftell (), etc.)

+5
source share
1 answer

fclosecalls closefor you. If you want to save fd after the call fclose, dupfd first.

int fd = open(...);
int fd2 = dup(fd);
FILE *fp = fdopen(fd2);
fclose(fp);
// fd is still valid.

The error message with the file descriptor in your example is delayed from the call fclose(dest1).

+13

All Articles