Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ FILE pointer to stdout?

Tags:

c++

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?

like image 488
Mitch Avatar asked Aug 23 '10 19:08

Mitch


People also ask

Is stdout a file pointer?

These three file pointers are automatically defined when a program executes and provide access to the keyboard and screen.

Is stdin a file pointer in C?

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.

What is stdout in C?

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 .

What type is stdin?

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.


2 Answers

stdout is a FILE*, so you can simply use:

FILE* fp = stdout;
like image 179
James McNellis Avatar answered Sep 21 '22 06:09

James McNellis


Just drop the ampersand: fp = stdout;.

like image 43
Dima Avatar answered Sep 21 '22 06:09

Dima