[英]Redirect some output to command prompt, and some to file?
I'm trying to redirect some of the standard output to a text file, and some other to the command prompt. 我试图重新定向某些标准输出到一个文本文件中,还有一些其他的命令提示符。
I'm currently outputting all of it to a file, but I'd like to output some to the command prompt, so I can know at least (get some hits), on what's been recorded (since it takes like 10 minutes to run this code) 我目前正在将所有内容输出到文件中,但我想将其输出到命令提示符下,因此我至少可以知道(得到一些匹配)记录的内容(因为运行大约需要10分钟)此代码)
This is what I'm doing; 这就是我在做什么;
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...";
Edit based on comment; 根据评论进行编辑;
'some' is part of the code where I would like to explicitly specify, example; “一些”是我想明确指定的示例代码的一部分;
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";
This might not be the best example but I hope you get the point. 这可能不是最好的例子,但我希望您明白这一点。
You could "abuse" standard output and standard error stream for that. 您可以为此“滥用”标准输出和标准错误流。 For example:
例如:
#include <iostream>
void main() {
std::cout << "standard output";
std::cerr << "standard error";
}
Now, if you redirect just the standard error to file... 现在,如果您仅将标准错误重定向到文件...
your_program.exe 2> file.txt
...you'll get "standard output" in console window and "standard error" in file.txt
. ...您将在控制台窗口中获得“标准输出”,并在
file.txt
“标准错误”。
(NOTE: This is Windows redirection syntax - I'm sure you'll have no trouble doing redirection on other OSes if you need to.) (注意:这是Windows重定向语法-如果您需要的话,我确定在其他操作系统上进行重定向不会有问题。)
I think this might help: 我认为这可能会有所帮助:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.