如何使用 STL 将 STDIN 转储到文件中C++

How to dump STDIN to a file, using C++ STL?

本文关键字:文件 C++ 转储 STDIN 何使用 STL      更新时间:2023-10-16

我正在编写这个程序,以便在此问题中做出解决方法:为什么在 subversion pre-revprop-change py 脚本中尝试 sys.stdin.read() 时出现"错误的文件描述符"?

注意:

  • 来自 STDIN 的内容可以是任意二进制数据。
  • 请使用C++ STL 函数、iostream、ifstream 等。
  • 如果文件创建/写入失败,我想捕获异常以了解情况。

大多数系统上最短的版本,也可能是最快的版本是:

#include <fstream>
#include <iostream>
int main() {
    std::ofstream("cin.txt", std::ios_base::binary) << std::cin.rdbuf();
}

我认为复制方法是你想要的:

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

例如:

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

这里的 fout 是一个文件流迭代器。