将一些输出重定向到命令提示符,将一些重定向到文件

Redirect some output to command prompt, and some to file?

本文关键字:重定向 文件 命令提示符 输出      更新时间:2023-10-16

我正在尝试将标准输出的部分重定向到文本文件,并将其他部分重定向到命令提示符。

我目前正在将所有这些输出到一个文件中,但我想将一些输出到命令提示符中,这样我至少可以知道(获得一些点击)记录了什么(因为运行此代码大约需要10分钟)

这就是我正在做的;

FILE *stream ;
std::stringstream ss;
ss << "K_file.txt";
if((stream = freopen(ss.str().c_str(), "w", stdout)) == NULL)
    exit(-1);
std::cout<<"blah blah blah...";

根据评论进行编辑;

"some"是我想明确指定的代码的一部分,例如;

for(int i = 0; i<1000; i++)
{
    std::cout<<"I would like this to go to the file - since it's detailed";
}    
std::cout<<"loop finished - I would like this to go to the command prompt";

这可能不是最好的例子,但我希望你能明白。

您可以"滥用"标准输出和标准错误流。例如:

#include <iostream>
void main() {
    std::cout << "standard output";
    std::cerr << "standard error";
}

现在,如果您将标准错误重定向到文件。。。

your_program.exe 2> file.txt

您将在控制台窗口中获得"标准输出",在file.txt中获得"错误"。

(注意:这是Windows重定向语法-如果需要的话,我相信你在其他操作系统上重定向不会有问题。)

我认为这可能会有所帮助:

#include <fstream>
#include <iostream>
class stream_redirector {
public:
    stream_redirector(std::ostream& dst, std::ostream& src)
        : src(src), sbuf(src.rdbuf())
    {
        src.rdbuf(dst.rdbuf());
    }
    ~stream_redirector() {
        src.rdbuf(sbuf);
    }
private:
    std::ostream& src;
    std::streambuf* const sbuf;
};
int main() {
    std::ofstream log("log.txt");
    std::cout << "Written to console." << std::endl;
    {
        // We redirect std::cout to log.
        stream_redirector redirect(log, std::cout);
        std::cout << "Written to log file" << std::endl;
        // When this scope ends, the destructor will undo the redirection.
    }
    std::cout << "Also written to console." << std::endl;
}