如何将cin和cout重定向到文件?

upd*_*liu 125 c++

我怎样才能重定向cinin.txtcoutout.txt

Naw*_*waz 197

以下是您想要做的工作示例.阅读注释以了解代码中的每一行.我用gcc 4.6.1在我的电脑上测试过它; 它工作正常.

#include <iostream>
#include <fstream>
#include <string>

void f()
{
    std::string line;
    while(std::getline(std::cin, line))  //input from the file in.txt
    {
        std::cout << line << "\n";   //output to the file out.txt
    }
}
int main()
{
    std::ifstream in("in.txt");
    std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf
    std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt!

    std::ofstream out("out.txt");
    std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf
    std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!

    std::string word;
    std::cin >> word;           //input from the file in.txt
    std::cout << word << "  ";  //output to the file out.txt

    f(); //call function


    std::cin.rdbuf(cinbuf);   //reset to standard input again
    std::cout.rdbuf(coutbuf); //reset to standard output again

    std::cin >> word;   //input from the standard input
    std::cout << word;  //output to the standard input
}
Run Code Online (Sandbox Code Playgroud)

您可以在一行中保存重定向:

auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save and redirect
Run Code Online (Sandbox Code Playgroud)

这里std::cin.rdbuf(in.rdbuf())设置std::cin'sbuffer to in.rdbuf()然后返回与之关联的旧缓冲区std::cin.可以使用std::cout- 或任何来完成同样的事情.

希望有所帮助.

  • 在将cin和cout重置为标准IO之前,是否需要关闭文件? (4认同)
  • @updogliu:不.如果你愿意,可以使用`in`和`out`分别读取和写入`in.txt`和`out.txt`.此外,当`in`和`out`超出范围时,文件将自动关闭. (3认同)

Tso*_*dze 84

写吧

#include <cstdio>
#include <iostream>
using namespace std;

int main()
{
    freopen("output.txt","w",stdout);
    cout<<"write in file";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 那是重定向`stdout`,而不是`cout`. (13认同)
  • 这也将重定向printf,这在某些情况下可能是一件好事. (5认同)
  • @AkshayLAradhya不是在设置[`std :: sync_with_studio(false);`](http://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio)时,虽然默认设置为`true` . (4认同)
  • 这比接受的答案+ 1简单得多 (3认同)
  • 如果答案在功能上相同,则C ++的等效形式为`ofstream out(“ out.txt”);。cout.rdbuf(out.rdbuf());`-仅多出一行,并且可移植。不那么简单:) (3认同)
  • @PřemyslŠťastný为什么? (2认同)
  • @nevelis很公平,你是对的。我想这取决于您是否需要将其便携式。我之所以要查找此代码,是为了测试编码挑战问题,所以我只想快速轻松地回答。显然,这与编写生产代码的人截然不同。 (2认同)

aei*_*eid 16

假设您的编译程序名称是x.exe,$是系统shell或提示符

$ x <infile >outfile 
Run Code Online (Sandbox Code Playgroud)

将从infile获取输入并输出到outfile.

  • 这与 C++ 无关,并且在任何重要示例中都失败了,例如,当您的程序生成写入控制台的子进程时。至少这是我在尝试这种重定向时遇到的问题,因此我在这里。 (2认同)

Vad*_*zim 16

这是一个用于阴影cin/cout的简短代码片段,可用于编程竞赛:

#include <bits/stdc++.h>

using namespace std;

int main() {
    ifstream cin("input.txt");
    ofstream cout("output.txt");

    int a, b;   
    cin >> a >> b;
    cout << a + b << endl;
}
Run Code Online (Sandbox Code Playgroud)

这提供了额外的好处,即普通fstream比同步的stdio流更快.但这仅适用于单一功能的范围.

全局cin/cout重定向可以写成:

#include <bits/stdc++.h>

using namespace std;

void func() {
    int a, b;
    std::cin >> a >> b;
    std::cout << a + b << endl;
}

int main() {
    ifstream cin("input.txt");
    ofstream cout("output.txt");

    // optional performance optimizations    
    ios_base::sync_with_stdio(false);
    std::cin.tie(0);

    std::cin.rdbuf(cin.rdbuf());
    std::cout.rdbuf(cout.rdbuf());

    func();
}
Run Code Online (Sandbox Code Playgroud)

请注意,ios_base::sync_with_stdio也重置std::cin.rdbuf.所以订单很重要.

另见ios_base :: sync_with_stdio的意义(false); cin.tie(NULL);

对于单个文件的范围,Std io流也可以很容易地被遮蔽,这对竞争性编程很有用:

#include <bits/stdc++.h>

using std::endl;

std::ifstream cin("input.txt");
std::ofstream cout("output.txt");

int a, b;

void read() {
    cin >> a >> b;
}

void write() {
    cout << a + b << endl;
}

int main() {
    read();
    write();
}
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,我们必须std逐个选择声明并避免using namespace std;因为它会产生歧义错误:

error: reference to 'cin' is ambiguous
     cin >> a >> b;
     ^
note: candidates are: 
std::ifstream cin
    ifstream cin("input.txt");
             ^
    In file test.cpp
std::istream std::cin
    extern istream cin;  /// Linked to standard input
                   ^
Run Code Online (Sandbox Code Playgroud)

另请参见如何在C++中正确使用名称空间?,为什么"使用命名空间std"被认为是不好的做法?以及如何解决C++命名空间和全局函数之间的名称冲突?


HaS*_*MiR 9

试试这个将cout重定向到文件。

#include <iostream>
#include <fstream>

int main()
{
    /** backup cout buffer and redirect to out.txt **/
    std::ofstream out("out.txt");

    auto *coutbuf = std::cout.rdbuf();
    std::cout.rdbuf(out.rdbuf());

    std::cout << "This will be redirected to file out.txt" << std::endl;

    /** reset cout buffer **/
    std::cout.rdbuf(coutbuf);

    std::cout << "This will be printed on console" << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

阅读全文使用 std::rdbuf 重定向 cin 和 cout

  • 该问题已在大约 6 年前(2012 年)得到解答,但您现在已在 2018 年添加了答案。您的答案与已接受的答案相同。所以我想知道为什么你在没有*任何* **新**添加的情况下发布这个? (3认同)
  • 我的回答没有混合 cout 和 cin 的重定向,我的版本分开以使其更具可读性 (3认同)
  • 您的答案中的*新*是什么*已接受*答案中没有的? (2认同)