-5

I'm writing this program so to make a workaround in this issue: Why do I get 'Bad file descriptor' when trying sys.stdin.read() in subversion pre-revprop-change py script?

Note:

  • Content from STDIN may be arbitrary binary data.
  • Please use C++ STL functions, iostream, ifstream etc .
  • If the file creation/writing failed, I'd like to catch the exception to know the case.
Community
  • 1
  • 1
Jimm Chen
  • 3,411
  • 3
  • 35
  • 59

2 Answers2

3

The shortest version and probably the fastest one on most systems is this:

#include <fstream>
#include <iostream>
int main() {
    std::ofstream("cin.txt", std::ios_base::binary) << std::cin.rdbuf();
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • Thank you very much, very concise. I added ios_base::binary to your code, otherwise, a single \n will be converted to \r\n on Windows. – Jimm Chen Sep 18 '12 at 12:29
  • Yeah, I noticed this issue. I'm a UNIX guy - it doesn't matter on UNIXes. – Dietmar Kühl Sep 18 '12 at 12:32
  • But... I tried, if cin.txt is read only, that ofstream code does not throw an exception. Could you do further improvement? – Jimm Chen Sep 18 '12 at 12:56
  • You can check the status of the expression in an `if` statement. To cause the stream to potentially throw (and potentially get some description of what went wrong) you'd need to set an exception mask (I never found a good use of stream exceptions, though). – Dietmar Kühl Sep 18 '12 at 13:03
  • Could you update the code? I just want to know whether cin.txt is written successfully, --which I think is a decent request. – Jimm Chen Sep 18 '12 at 13:12
1

I think copy method is what you want:

template<class InputIterator, class OutputIterator>
OutputIterator copy ( InputIterator first, InputIterator last, OutputIterator result )
{
  while (first!=last) *result++ = *first++;
  return result;
}

for example:

copy(istream_iterator<string>(cin)
       , istream_iterator<string>()
       , ostream_iterator<string>(fout, "\n"));

here the fout is a file stream iterator.

rpbear
  • 640
  • 7
  • 15
  • 1
    I assume you meant to point out this is [`std::copy`](http://en.cppreference.com/w/cpp/algorithm/copy), and this is just an example implementation. – BoBTFish Sep 18 '12 at 09:43