freopen()等效于c ++流

当使用c风格的i / o进行编程时,我有时会使用freopen()来重新打开stdin以进行测试,这样我就不必一遍又一遍地重新输入输入。 我想知道是否有相当于c ++的i / o流。 此外,我知道我可以使用管道在命令行/终端/无论如何重定向它,但我想知道是否有办法在我的代码中执行它(因为你可以看到,我不是很了解CL / T / W)。

freopen也适用于cincout 。 无需搜索新内容。

 freopen("input.txt", "r", stdin); // redirects standard input freopen("output.txt", "w", stdout); // redirects standard output int x; cin >> x; // reads from input.txt cout << x << endl; // writes to output.txt 

编辑:从C ++标准27.3.1:

对象cin控制与在声明的对象stdin相关联的流缓冲区的输入。

所以根据标准,如果我们重定向stdin它也会重定向cincout反之亦然。

 #include  #include  int main() { // Read one line from stdin std::string line; std::getline(std::cin, line); std::cout << line << "\n"; // Read a line from /etc/issue std::ifstream issue("/etc/issue"); std::streambuf* issue_buf = issue.rdbuf(); std::streambuf* cin_buf = std::cin.rdbuf(issue_buf); std::getline(std::cin, line); std::cout << line << "\n"; // Restore sanity and read a line from stdin std::cin.rdbuf(cin_buf); std::getline(std::cin, line); std::cout << line << "\n"; } 

http://www.cplusplus.com/reference/iostream/ios/rdbuf/

此新闻组post探讨了您的选择。

这取决于系统,海报没有显示系统,但cin.clear()应该有效。 我已经在带有AT&T版本iostream的UNIX系统上测试了附加程序。

 #include  int main() { for(;;) { if ( cin.eof() ) { cout << "EOF" << endl; cin.clear(); } char c ; if ( cin.get(c) ) cout.put(c) ; } } 

是的,这在cfront和TC ++中运行正常。 在g ++中,问题首先出现时需要执行其他操作:

  cin.clear(); rewind ( _iob ); // Seems quite out of place, doesn't it? // cfront also accepts but doesn't // require this rewind. 

虽然我注意到这是在1991年,它应该仍然有效。 请记住使用现在标准的iostream标头,而不是iostream.h

(顺便说一下,我发现谷歌搜索词的post“重新打开cin c ++”,第二个结果。)

让我们知道您的身体情况如何。 你也可以使用freopen