0

Visual Studio 2022 - Community Edition

I would like versions of the C++ fstream, ifsteam, and ofstream classes that operate identically to the standard versions except that some of the functions they contain also call some custom functions I wrote. Is there any reasonable way to accomplish this? It seems there might be some way to "intercept" calls to the standard functions, execute my own code, then let the standard functions continue, but I don't know enough about C++ at that level to know how to do it or if it would even be possible. I'd like to do this for the class constructors and any other functions that open, read, write, or close files. I've toyed with possibly modifying the standard library header files themselves but I don't really want to open that can of worms. Any information would be greatly appreciated.

BenevolentDeity
  • 693
  • 1
  • 4
  • 18
  • It depends. `std::fstream`, `std::ifstream`, and `std::ofstream` are all specialisations of template classes, but have base classes (some in common). If the functions you're trying to intercept are inherited virtual functions, you can derive classes and override. If you're trying to intercept non-virtual functions, then use a wrapper class - with caveat that your objects cannot be passed to arbitrary functions that expect standard stream objects. The stream classes also manage a stream buffer (as a distinct object) and you may be able to tailor a stream buffer type and intercept its operations – Peter Apr 18 '22 at 09:24
  • 1
    Most classes in the standard library are not designed to be inherited from. But I think the best customization-point in the streaming part of the std library is `std::basic_streambuf`. You can see some examples online i.e. https://siware.dev/007-cpp-custom-streambuf/ or this: https://web.archive.org/web/20160331011817/http://www.mr-edd.co.uk/blog/beginners_guide_streambuf – PeterT Apr 18 '22 at 09:28

0 Answers0