I'm writing a program and I want the user to be able to specify whether the output is written to a file or to stdout. Until this point, my program has been using printf commands, so I was hoping to simply change the commands to fprintf commands, but my compiler is shouting at me because obviously, they are not the same object classes.
For example:
FILE *fp;
bool print_to_file;
.
.
.
if(print_to_file){
fp = fopen("something.txt", "w");
}
else{
fp = &stdout;
}
fprintf(fp,"%s\t%s\t%s\n",string1 . c_str(), string2 . c_str(), string3 . c_str());
I'd prefer to stick with fprintf and find a FILE pointer to stdout, does anyone know if that's possible? If the answer is no, can I open my files as fstreams, and then use fprintf?
These three file pointers are automatically defined when a program executes and provide access to the keyboard and screen.
The “stdin” is also known as the pointer because the developers access the data from the users or files and can perform an action on them. In this write-up, we will use the built-in functions of C programming that can be used to read the input by the stdin.
stdout stands for standard output stream and it is a stream which is available to your program by the operating system itself. It is already available to your program from the beginning together with stdin and stderr .
Short for standard input, stdin is an input stream where data is sent to and read by a program. It is a file descriptor in Unix-like operating systems, and programming languages, such as C, Perl, and Java.
stdout
is a FILE*
, so you can simply use:
FILE* fp = stdout;
Just drop the ampersand: fp = stdout;
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With