How to write console output to a text file in cpp?

亡梦爱人 提交于 2020-01-11 05:30:20

问题


I'm trying to write console data into a separate text file in cpp. Anybody help me with sample code.


回答1:


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.




回答2:


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.




回答3:


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);
}



回答4:


bbtrb wrote:

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.




回答5:


smerrimans answer should help you out.

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.

You will need to read up a little bit on how it works and this book helped me get it right.

If that's not what you're after it is a bit of overkill though.



来源:https://stackoverflow.com/questions/3270847/how-to-write-console-output-to-a-text-file-in-cpp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!