C++ 如何将控制台输出写入 cpp 中的文本文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3270847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write console output to a text file in cpp?
提问by Naveen kumar
I'm trying to write console data into a separate text file in cpp. Anybody help me with sample code.
我正在尝试将控制台数据写入 cpp 中的单独文本文件。任何人都可以帮助我提供示例代码。
回答by user11977
There are various ways to do this. You could redirect it from the command line with programname > out.txt
. Or you could use freopen("out.txt","w",stdout);
at the start of your program.
有多种方法可以做到这一点。您可以使用programname > out.txt
. 或者您可以freopen("out.txt","w",stdout);
在程序开始时使用。
回答by bbtrb
If you want to write from your own process, I'd suggest a simple print method
如果您想从自己的过程中编写,我建议使用简单的打印方法
void print(const string str, ostream & output)
{
output << str;
}
Then you can call
然后你可以打电话
print("Print this", cout);
for console output, or
用于控制台输出,或
ofstream filestream("filename.out");
print("Print this", filestream);
to write into a file "filename.out". Of course you gain most, if print
is a class method that outputs all the object's specific information you need and this way you can direct the output easily to different streams.
写入文件“filename.out”。当然你获得的最多,如果print
是一个类方法,它输出你需要的所有对象的特定信息,这样你就可以轻松地将输出定向到不同的流。
回答by Hossein
bbtrb wrote:
bbtrb 写道:
void print(const string str, ostream & output) { output << str; }
void print(const string str, ostream & output) { output << str; }
Better than this is of course
当然比这更好
ostream& output(ostream& out, string str) {out << str; return out;}
so that you can even have the manipulated output stream returned by the function.
这样您甚至可以拥有该函数返回的操纵输出流。
回答by Mattias Nilsson
smerrimans answer should help you out.
smerrimans 的回答应该可以帮助你。
There is also the option to implement your own streambuf and use it with std::cout and std::cerr to store printouts to file instead of printing to console. I did that a while ago to redirect printouts to some sort of rotating logs with timestamps.
还可以选择实现您自己的流缓冲并将其与 std::cout 和 std::cerr 一起使用以将打印输出存储到文件而不是打印到控制台。不久前我这样做是为了将打印输出重定向到某种带有时间戳的旋转日志。
You will need to read up a little bit on how it works and this bookhelped me get it right.
你需要阅读一些它是如何工作的,这本书帮助我把它弄对了。
If that's not what you're after it is a bit of overkill though.
如果这不是你所追求的,那就有点矫枉过正了。
回答by domachine
If you want to create a child process and redirect its output you could do something like this:
如果要创建子进程并重定向其输出,可以执行以下操作:
FILE* filePtr = popen("mycmd");
FILE* outputPtr = fopen("myfile.txt");
if(filePtr && outputPtr) {
char tmp;
while((tmp = getc(filePtr)) != EOF)
putc(tmp, outputPtr);
pclose(filePtr);
fclose(outputPtr);
}