Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect cin and cout to files?

Tags:

c++

How can I redirect cin to in.txt and cout to out.txt?

like image 317
updogliu Avatar asked Apr 14 '12 02:04

updogliu


People also ask

How do you redirect in C++?

I/O Redirection in C++FILE * freopen ( const char * filename, const char * mode, FILE * stream ); For Example, to redirect the stdout to say a textfile, we could write : freopen ("text_file. txt", "w", stdout);

Can we use cout and cin in C?

cin and cout are streams and do not exist in C. You can use printf() and scanf() in C.


2 Answers

Here is an working example of what you want to do. Read the comments to know what each line in the code does. I've tested it on my pc with gcc 4.6.1; it works fine.

#include <iostream> #include <fstream> #include <string>  void f() {     std::string line;     while(std::getline(std::cin, line))  //input from the file in.txt     {         std::cout << line << "\n";   //output to the file out.txt     } } int main() {     std::ifstream in("in.txt");     std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf     std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt!      std::ofstream out("out.txt");     std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf     std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!      std::string word;     std::cin >> word;           //input from the file in.txt     std::cout << word << "  ";  //output to the file out.txt      f(); //call function       std::cin.rdbuf(cinbuf);   //reset to standard input again     std::cout.rdbuf(coutbuf); //reset to standard output again      std::cin >> word;   //input from the standard input     std::cout << word;  //output to the standard input } 

You could save and redirect in just one line as:

auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save and redirect 

Here std::cin.rdbuf(in.rdbuf()) sets std::cin's buffer to in.rdbuf() and then returns the old buffer associated with std::cin. The very same can be done with std::cout — or any stream for that matter.

Hope that helps.

like image 70
Nawaz Avatar answered Oct 21 '22 21:10

Nawaz


Just write

#include <cstdio> #include <iostream> using namespace std;  int main() {     freopen("output.txt","w",stdout);     cout<<"write in file";     return 0; } 
like image 30
Tsotne Tabidze Avatar answered Oct 21 '22 22:10

Tsotne Tabidze