Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does fdopen have a "flags" argument?

Tags:

c

I'm never really sure what open mode I'm supposed to pass to fdopen, or why it even has an open mode. Since fdopen operates on a file descriptor which may have previously been opened via a lower level call like open - which already sets the mode flags.

I mean, I assumed that any implementation of fopen would just translate the char* mode string into a lower level mode flag type, (an OR'd int on POSIX systems), and then pass that to open.

But if we're calling fdopen where we have an existing file descriptor that came from a previous call to open, why do we need flags? It just seems to create more work for the programmer to translate the int flags into char* flags for fdopen.

Am I missing some use case where we might want different flags for open and fdopen?

like image 980
Siler Avatar asked Feb 06 '26 23:02

Siler


2 Answers

Maybe you want to pass O_RDWR to open(2) and then "r" to fdopen(3). That is a perfectly legal thing to do. Perhaps someone else called open(2) and/or fdopen(3) on your behalf.

like image 73
Kevin Avatar answered Feb 08 '26 15:02

Kevin


Kevin shared the proper idea.

FILE * and fd are governed by different instances. since open modes are most likely being hard coded, so it's trivial for programmers to type it twice.

there are indeed some cases you will want to open something in fd first then wrap it to FILE * afterwards. for example, before i tried to provide a serial port interface in my own project, i had to open it using open, so that i could operate ioctl, termios on it, and finally, i wrapped it with a FILE * so that allowed the external world to use fgets or stuff like that.

like image 43
Jason Hu Avatar answered Feb 08 '26 13:02

Jason Hu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!