Is it possible to rescue file descriptor from FILE*?

雨燕双飞 提交于 2019-12-02 05:45:17

Supposing that fd is your file descriptor and f your FILE* got from it. Maybe something like the following will do the trick:

fd2 = dup(fd);
fclose(f);
dup2(fd2, fd);
close(fd2);

My problem is that fclose used to clean up FILE* objects closes connected file descriptor.

You could use dup(2) to get a copy of the descriptor. Then the close(2) that fclose(3) does won't do anything.

I need to maintain exact same fd number

Then call dup2 again after fclose: dup2(savedfd, rescuedfd)

When you get a file descriptor from another source, Try to get its filename from that file descriptor. (Some says its possible using platform specific method. -google it.)

Once you get filename then fopen it again and get FILE* and do your work and clean up it using fclose.

Your original fd will not be disturbed.

Here's a non-portable idea (vote if you think this is good/best):

GNU libc provides fopencookie and BSD provides equivalent funopen.

These return real FILE* handle, but implementation is your own:

It is then relatively trivial to map read/write/seek/close functions to underlying system calls:

read/readfn(cookie, buf, size){ return read((int)cookie, buf, size); }
write/writefn(cookie, buf, size) { return write((int)cookie, buf, size); }
seek/seekfn(cookie, offs, arg) { return seek((int)cookie, offs, arg); } // may require arg mapping to whence
close/closefn(cookie) {} // that's the whole point!
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!