混合fdopen()和open() - GT;坏文件描述符 [英] Mixing fdopen() and open() -> bad file descriptor

查看:280
本文介绍了混合fdopen()和open() - GT;坏文件描述符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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开放流()?

I don't understand why? How can I successfully mix stream based IO with open()?

这是我仅有的工作库接受整数FD(和图书馆是关闭它,$ P $紧密psumably()内部负责),但我仍然需要用文件来工作,我不T看看如何正确地是没有可能的f()的调用,例如(FREAD(),FTELL()等)

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 要求关闭为您服务。如果你想打电话后围绕保持FD FCLOSE DUP 的FD第一。

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.

在你的榜样,坏的文件描述符错误消息是从 FCLOSE(dest1)通话挥之不去。

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

这篇关于混合fdopen()和open() - GT;坏文件描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆