将一些输出重定向到命令提示符,将一些重定向到文件
Redirect some output to command prompt, and some to file?
我正在尝试将标准输出的部分重定向到文本文件,并将其他部分重定向到命令提示符。
我目前正在将所有这些输出到一个文件中,但我想将一些输出到命令提示符中,这样我至少可以知道(获得一些点击)记录了什么(因为运行此代码大约需要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;
}
相关文章:
- 获取通过重定向传入的输入文件的名称?
- 写入文件 a.txt,而终端重定向到文件 b.txt
- 将 clangd stderr 重定向到文件而不是控制台
- 是否可以将子进程的 stdout 重定向到父进程中的另一个文件?
- 重定向输入和输出时如何处理主文件I/O?
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- 可以将Boost消息队列文件重定向到用户指定的位置
- 如何使用PHP将上传到本地主机的一个html文件重定向到磁盘上的另一个html文档
- 尝试将 std::cerr 重定向到文件时出现访问冲突异常
- 重定向到文件的C ++ COUT比使用Ofstream慢
- 将 Tcl 中的命令输出重定向到文件时,文件以 DOS 格式生成
- 将 c++ 程序语法错误重定向到窗口中的文件
- 如何在没有任何缓冲区的情况下将 stderr 重定向到文件?
- 将 ffmpeg 控制台输出重定向到C++中的字符串或文件
- Win32 GUI C(++) 应用将标准输出和标准输出重定向到磁盘上的同一文件
- 即使可执行文件的输入是从文件重定向的,如何强制从终端输入?
- C++输入重定向导致文件参数工作时出错
- C++ vector<pair<int,int>> std::all_of() 函数问题(重定向到头文件)
- 重定向文件访问
- Boost.IOStreams:如何使用"rdbuf"正确重定向文件流?