2011-12-07 54 views
5
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 

我不明白爲什麼?我如何成功地將基於流的IO與open()混合?混合fdopen()和open() - >壞的文件描述符

我正在使用的一個庫只接受一個整數fd(並且庫在內部負責關閉它,大概是用close()),但我仍然需要使用該文件,而且我不需要如果沒有f()調用(如fread(),ftell()等),看看這是如何實現的。

回答

13

fclose請致電close。如果您想在fd第一次撥打fclose,dup後保持fd。

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

您示例中的錯誤文件描述符錯誤消息是從fclose(dest1)調用中逗留的。

+0

謝謝!我沒有仔細閱讀手冊頁,因爲fdopen()手冊頁與freopen()和fopen()混合在一起:/ – Blub