Home > database >  Can I use file descriptors and file pointers in the same program?
Can I use file descriptors and file pointers in the same program?

Time:10-25

Is it possible to use file pointers and file descriptors in the same program?

IMO, I feel like it should be okay to mix them because the pointer and descriptors are two separate variables even though they point to the same file, but at the same time, I feel like its not okay because if I write something using file pointers, it won't be updated in the file descriptor?

CodePudding user response:

Is it possible? Of course. C lets you do all kinds of weird and bad stuff. The real question is whether or not it is a good idea.

First, read through this question. It is important to note that file descriptors are merely integers to represent a "thing" that the OS can read/write to (not just files, also sockets and more). On the other hand, file pointers (FILE *) are just file descriptors bundled up into a nice struct and a bunch of easy-to-use functions in libc.

Almost always, if you are reading from an actual file, like from a disk, then you should use a file pointer. Otherwise, use a file descriptor (ex: a socket).

Because of this, there are legit reasons to use both in the same program. You might want to read from a config file using a file pointer and then open a socket using a file descriptor. However, don't use both a file pointer and a file descriptor for the same resource, unless you are absolutely forced to do so.

  •  Tags:  
  • c
  • Related