2

I've read that it's possible to read cin via an ifstream by changing the buffer, but is it safe? What are the disadvantages to doing it this way:

file.ios::rdbuf(cin.rdbuf());

Thanks

C++: UNIX - defaulting ifstream variable to standard input
iostream - C++: assign cin to an ifstream variable? - Stack Overflow

Community
  • 1
  • 1
loop
  • 3,460
  • 5
  • 34
  • 57

1 Answers1

1

Yes, it is safe, that is the entire reason that the rdbuf functions exist.

It's also one of the major reasons that iostreams are dog slow. An ifstream object isn't necessarily attached to a file. A stringstream object might be attached to a file. Lots of polymorphism, lots of virtual calls, no chance for optimization.

But you pay for those disadvantages whether you rebind streams or not.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • My original example was wrong, can you look over the edit? I have some code that uses an ifstream and I wanted to pass cin instead. I'm thinking of `file.ios::rdbuf(cin.rdbuf());` but I don't know if that's ok. As long as the code doesn't call open or close on file is it ok? – loop Feb 25 '14 at 04:48
  • Disagree with sentiment. The virtual calls in `rdbuf` are not going to slow down File I/O, and formatted I/O isn't that fast either. If you're doing unformatted I/O, you can directly call the `streambuf` methods skipping the abstraction cost too. – MSalters Feb 25 '14 at 08:10
  • MSalters, disagree all you want, I have profiler data forming the basis of my statements. Note that the calls I'm talking about are not in rdbuf. However rdbuf cannot exist without the polymorphic pimpl machinery. – Ben Voigt Feb 25 '14 at 14:58
  • @Ben If you could respond to my original comment, so that I can mark this answer you gave correct if it is so. Thanks – loop Mar 05 '14 at 19:29
  • @test: your edit didn't require any change to the answer. You can associate a file with cin and the reverse also works. – Ben Voigt Mar 05 '14 at 20:04