In addition to afr0ck, the answer is freopen () I want to say that when using freopen() we have to be careful. When a stream, like stdout or stdin , opens again with a new destination (here 'output.txt' ), it always remains for the program, unless it has clearly changed.
freopen("output.txt", "a", stdout);
Here, the standard output stream stdout reopened and assigned by the file 'output.txt' . After that, whenever we use printf() or any other stdout stream, such as putchar() , each output will go to 'output.txt' . To return the default behavior (i.e. print the output in the console / terminal) printf() or putchar() , we can use the following line of code -
- for gcc, a Linux distribution, for example ubuntu,
freopen("/dev/tty", "w", stdout); - for Mingw C / C ++, windows -
freopen("CON", "w", stdout);
See the code example below -
#include <stdio.h> int main() { printf("No#1. This line goes to terminal/console\n"); freopen("output.txt", "a", stdout); printf("No#2. This line goes to the \"output.txt\" file\n"); printf("No#3. This line aslo goes to the \"output.txt\" file\n"); freopen("/dev/tty", "w", stdout); /*for gcc, diffrent linux distro eg. - ubuntu*/ //freopen("CON", "w", stdout); /*Mingw C++; Windows*/ printf("No#4. This line again goes to terminal/console\n"); }
This code generates the file 'output.txt' in your current directory, and No # 2 and No # 3 will be printed in the 'output.txt' file.
thanks
source share