Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

cmd

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

like image 844
Naveen kumar Avatar asked Jul 17 '10 08:07

Naveen kumar


2 Answers

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.

like image 138
user11977 Avatar answered Nov 16 '22 20:11

user11977


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.

like image 33
bbtrb Avatar answered Nov 16 '22 21:11

bbtrb