1

Can I retrieve information about a file previously opened with fopen() using only the pointer it returned?

The reason I ask is that I am trying to write a RAII-style wrapper class for FILE *s, and I want to make it as general as possible, and one of the functions I imagined for it was a copy-like operation, that would take a FILE * as an argument, and create a new reference to the same file.

Under POSIX, I can create a duplicate of a file descriptor with dup()/dup2(), and even get how the file is being accessed with fnctl()'s F_GETFL operation. However, even if I do that to the underlying descriptor of a FILE *, it isn't enough for guessing properties such as if the stream is text or binary (under POSIX, there no real difference, but I want to be general), or its orientation towards char- or wchar_t-based text.

So, is there is a way of learning about the stream I'm about to create a wrapper for, how far can I go, and how should I do it?

Thank you for you attention.

Paulo1205
  • 918
  • 4
  • 9
  • What kind of information? Data contained within a file? What do you mean by information about a file? –  May 19 '20 at 00:27
  • [man fgets()](https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm) –  May 19 '20 at 00:28
  • Is it perhaps an option to make a non-copyable internal type and handle that thing with a `shared_ptr`? Or perhaps bake your own refcounting? It would avoid the necessity to use the operating system's refcounting. – bitmask May 19 '20 at 00:28
  • @Asadefa, not the data in a file, but aspects about it, such as the mode it was opened with, if `fwide()` was applied to it, what kind of buffering it is using, and things like that. Note that these are all open-time or close-to-open-time information, since neither `setvbuf()` nor `fwide()` are supposed to be called at any other time than just right after `fopen()`, and before any reading or writing takes place. – Paulo1205 May 19 '20 at 00:40
  • Why would you want to have two `FILE*` streams for one open file description? What with the buffering (in general), that seems more trouble than useful. Why wouldn’t you just want to reuse the `FILE*` if you’re going to share the description anyway? – Davis Herring May 21 '20 at 02:43
  • @DavisHerring, I don't. What I wanted to do was to get information about the file modes of operation to possibly replicate them (with occasional variations) in a second `FILE *` with a different file underlying descriptor altogether, so different parts of the program (different sub-programs, really) could work on the same file in an independent but consistent way. – Paulo1205 Aug 03 '20 at 03:40
  • @Paulo1205: That’s not what `dup`/`dup2` do, though. – Davis Herring Aug 03 '20 at 03:56

0 Answers0